Dependency Injection in ASP.NET MVC3
What dependency injection means is that instead of writing code like this in your controller
you write code like this
the benefits of dependency injection are your classes are not tightly coupled, are more testable, and really is pluggable.
To enable dependency injection into your controllers in ASP.NET MVC2 you had to create a new class derived from DefaultControllerFactory and override the GetControllerInstance method to create the controller using your dependency injection container e.g.
and then you had to register this controller factory as the default in the Application_Start event in the global.ascx file
The problem here is that you need to create a separate custom class for the model binders, and for custom model metadata.
ASP.NET MVC 3 makes things easier to inject dependencies by introducing a new interface IDependencyResolver. The benefit here is that this DependencyResolver is responsible to resolve dependencies not only for the controller but also for the services (repository, logger etc.) consumed by the controller, view engine, view binders, and the model and model metadata.
The interface has two methods
which return either a single object or a list of object of serviceType. If a type cannot be resolved by the dependency resolver then ASP.NET MVC3 expects the resolver to return null.
If the dependency resolver returns null then ASP.NET MVC3 will fall back to the default factory class to instantiate the interface object.
To use this new interface simply create a new class which implements this interface
I’m using Unity as my dependency container and since Unity throws a ResolutionFailedException exception if it cannot resolve a type we need to wrap it in a try/catch block and return null in case of exception.
Just like the controller factory we need to register our dependency resolver at Application_Start event in our global.ascx
You can either configure your container at runtime or via the .config file. I prefer the .config approach because then I can easily take my application to any environment (DEv vs QA) and switch out my EmailLogger with NullLogger or as required by changing the mapping in the .config file.