Ninject property injection returns null

别来无恙 提交于 2019-12-22 04:27:31

问题


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

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

For the Module.Load() event:

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

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.

Thoughts?


回答1:


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
}



回答2:


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).

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)

See also:

IoC/DI framworks with Smart Client Winform apps: How should I approach this?

What is the best practice for WinForms dialogs with ninject?



来源:https://stackoverflow.com/questions/3552774/ninject-property-injection-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!