简体   繁体   English

Ninject属性注入返回null

[英]Ninject property injection returns null

I've got a WinForms app with the following code: 我有一个WinForms应用程序,代码如下:

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

For the Module.Load() event: 对于Module.Load()事件:

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

At this point test in the Main() method is the proper object I'm expecting. 此时, Main()方法中的test是我期望的正确对象。

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. 一旦表单加载,尝试使用test ,但它是一个空对象。

Thoughts? 思考?

Make sure you call Inject() on the IKernel instance and pass in an instance of your form. 确保在IKernel实例上调用Inject()并传入表单实例。 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
}

Instead of doing 而不是做

var form = new MainForm()

... ...

class MainForm
{
    MainForm()
    {
        GlobalKernel.Inject(this)

.... ....

You want to be doing: 你想要做:

var form = Kernel.Get<MainForm>()

Which obviates the need for the explicit Inject (and allows you to do constructor injection). 这样就不需要显式的Inject(并允许你进行构造函数注入)。

I dont know of any WinForms (or WPF) samples for Ninject (but it'd be a good question to ask and/or stick a bounty on -- IIRC one came up recently) 我不知道Ninject的任何WinForms(或WPF)样本(但这是一个很好的问题要求和/或坚持奖励 - 最近出现了IIRC)

See also: 也可以看看:

IoC/DI framworks with Smart Client Winform apps: How should I approach this? 使用Smart Client Winform应用程序的IoC / DI框架:我该如何处理?

What is the best practice for WinForms dialogs with ninject? 使用ninject的WinForms对话框的最佳实践是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM