使用Ninject将依赖项注入到外部构造的对象中(用户控件) [英] Using Ninject to inject dependencies into externally constructed objects (user control)

查看:119
本文介绍了使用Ninject将依赖项注入到外部构造的对象中(用户控件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在WinForms应用程序中使用Ninject.我无法弄清楚如何将其用于用户控件.有时,它们依赖于我想通过DI框架配置的服务.这些控件需要通过设计器进行管理(因此需要默认的构造函数).

I would like to use Ninject in my WinForms application. I cannot figure out how to use it for my user controls. Sometimes they rely on the services I want to configure through the DI framework. These controls need to be manageable through the designer (thus need default constructors).

那么,有没有一种方法可以将依赖项注入到该用户控件的属性中?由于设计者需要能够构造它,因此kernel.Get<TestClass>在这里将无法工作.是否有一种方法或一些代码可以让我填充" Form_OnLoad()方法中的依赖项?

So, is there a way to inject dependencies into properties of this user control? Since the designer needs to be able to construct it, kernel.Get<TestClass> won't work here. Is there a method or some code that will let me "fill-in" the dependencies in the Form_OnLoad() method?

我还可以想到其他一些示例,在这些示例中,我想向已经存在的对象的属性中注入信息,但是WinForms用户控件最容易解释.

I can also think of other examples where I would want to Inject into the properties of an already existing object, but th WinForms user control is the easiest to explain.

推荐答案

我认为您需要颠倒思维.在模型视图控制器中,视图仅具有一项职责:显示数据.

I think you need to invert your thinking. In Model View Controller, the View has only one responsibility: to display data.

数据如何到达那里是控制器的责任,数据如何在内存中表示由模型决定.

How that data gets there is the Controller's responsibility, and how the data is represented in memory is determined by the Model.

尽管没有用于Windows窗体的特定MVC框架,但是可以手动制作粗略的框架,或者您可以去看看(现已退休)

Although there are no specific MVC frameworks for Windows Forms, it's possible to make crude ones manually, or you could go have a look at the (now retired) Composite Application Block to get an idea about how this can be done (although the CAB is perhaps too complicated for most people's tastes). There are more elegant options available today, but they involve WPF.

在任何情况下,不要将依赖项注入视图中,而应将其注入控制器中,并让控制器实例化并正确填充视图(您的控件).

In any case, instead of injecting your dependencies into your Views, inject them into Controllers, and have the Controllers instantiate and correctly populate the Views (your Controls).

通过这种方式,您可以使控件不受DI顾虑的影响.

In this way, you can keep your Controls free of DI concerns, as they should be.

这篇关于使用Ninject将依赖项注入到外部构造的对象中(用户控件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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