Ninject物业注入返回null [英] Ninject property injection returns null

查看:131
本文介绍了Ninject物业注入返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码WinForms应用程序:

I've got a WinForms app with the following code:

static void Main()
{
    IKernel kernel = new StandardKernel(new MyModule());
    TestInterface test = kernel.Get<TestInterface>();
}

有关的Module.Load()事件:

For the Module.Load() event:

Bind<TestClass>().ToSelf().InSingletonScope();
Bind<TestInterface>().To<TestClass>();



此时测试的Main()方法是我期待适当的对象。

At this point test in the Main() method is the proper object I'm expecting.

在以后一种形式,我使用的财产注:

In a form later on, I'm using property injection:

[Inject]
TestInterface test {get;set;}

一旦加载窗体,试图用测试,但它是一个空对象。

And once the form is loaded, trying to work with test, but it's a null object.

思考?

推荐答案

请确保你调用注入( )对表单的一个实例的iKernel实例和传球。这将确保所有相关性注入正确。例如...

Make sure you call Inject() on the IKernel instance and pass in an instance of your form. This will ensure all dependencies are properly injected. For example...

[Inject]
TestInterface Test { get; set; }

private void Form_Load(object sender, EventArgs e)
{            
    IKernel kernel = ... // Get an instance of IKernel
    kernel.Inject(this);

    // Your form dependencies have now been injected and the 
    // Test property is ready to use
}

这篇关于Ninject物业注入返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆