.NET – Best Way to Build a Factory Using NInject

dependency-injectiondesign-patternsnetunit testing

I am pretty comfortable with dependency injection using NInject in MVC3. While working in an MVC3 application, I developed a custom Controller Creation Factory using NInject, so any controller that is created will have dependencies injected in it through this Controller Factory.

Now I am starting to develop a windows application, I want to use Application wide Dependency Injection. i.e. Every object must be created through NInject, so as to ease Unit Testing. Please guide me to ensure that every object created must be though the NInject Factory only.

For example, if on any windows form on Button_Click event I write:

TestClass testClass = new TestClass()

and TestClass has any dependency on, say, ITest then it must be automatically resolved. I know I can use:

Ikernel kernel = new StandardKenel()
//AddBinding()
TestClass testClass = kenel.get<TestClass>();

But I find it tedious to do this every time I want to create an object. It also the forces developer to create the object in a particular way. Can it be made better?

Can I have a central repository for object creation and then every object creation will automatically use that repository?

Best Answer

For client applications, it's often best to adapt a pattern like MVP (or MVVM) and use data-binding from the form to the underlying ViewModel or Presenter.

For the ViewModels, you can inject the required dependencies using standard Constructor Injection.

In your application's Composition Root you can wire up the entire object graph for your application. You don't need to use a DI Container (such as Ninject) for this, but you can.