Ninject 属性注入返回 null
我有一个带有以下代码的 WinForms 应用程序:
static void Main()
{
IKernel kernel = new StandardKernel(new MyModule());
TestInterface test = kernel.Get<TestInterface>();
}
对于 Module.Load() 事件:
Bind<TestClass>().ToSelf().InSingletonScope();
Bind<TestInterface>().To<TestClass>();
此时 Main()
方法中的 test
是正确的对象我正在期待着。
在稍后的表单中,我使用属性注入:
[Inject]
TestInterface test {get;set;}
加载表单后,尝试使用 test
,但它是一个空对象。
想法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确保在 IKernel 实例上调用 Inject() 并传入表单的实例。这将确保正确注入所有依赖项。例如...
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 的需要(并允许您进行构造函数注入)。
我不知道 Ninject 的任何 WinForms(或 WPF)示例(但这是一个很好的问题,可以提出和/或悬赏 - IIRC 最近出现了一个)
另请参阅:
IoC/DI 框架与智能客户端 Winform 应用程序:我应该如何处理这个?
最佳实践是什么WinForms 对话框与 ninject?
Instead of doing
...
....
You want to be doing:
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?