views:

236

answers:

1

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

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?

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.

+1  A: 

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.

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

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

Mark Seemann
Ok, I see that the controllers should eventually have the dependencies. I've been doing MVC with the View created first, then it creates the Controller. Since User Controls are always going to be created by the form or other controls, should Controllers be created along a separate path?
Nathan
Am I wrong to use kernel.Inject(myControl) when myControl has Properties that are attributed with [Inject]?
Nathan
You could do that as long as you realize that this means taking a dependency on Ninject itself.
Mark Seemann