An MVC 2 sample implementation of Dependency Injection pattern

11/4/2010 10:53:00 PM

The Dependency Injection pattern brings huge positive effects on your design and code maintainability. But how to implement it correct?

The Dependency Injection Pattern is a popular design technique that can be used to implement loosely coupled, reusable, and testable objects in software designs by reducing the cohesion amongst the components in your application.

This basic article introduces how to implement the pattern in VS and ASP.NET MVC2.

Dependency Injection using the ASP.NET MVC Framework 2.0

After a first try I'm a bit stunned how easy it is to get it running and it fits MVC like a glove with the suggested extension of the DefaultControllerFactory. No need to register the controllers into the IoC container, somehow it's done automatically. All interface constructor parameters to the controllers are resolved as well. 

The other thing, that I haven't realized before, is that this is not only good for easily switching implementation of your components interfaces easily. It also is a great way of handling the configuration of your components as there are several ways to define parameters (constructor parameters, public properties) in your configuration of the container (which can be done in your app configuration). No need to let your components load configuration parameters, let Unity map them.

Implementing Unity (or any DI framework) will sure give a new way of implementing things. It will naturally encourage loose coupling and using interfaces without giving a feel of a hazzle. I'm looking forward to start using this in a real project soon, booth for vertical concerns and cross cutting concerns.

Try it, you'll like it!