Blog

Dependency Injection in MVC3

By Carlos Martinez

Dependency Injection is a form of Inversion of control where the dependent objects are injected into a class, instead of creating an instance.

The usual way to implement this pattern is using an object container and plain objects. Each container injects the entire requested objects based on a previous configuration.

A new interface is available in MVC 3, called “IDependencyResolver”. This interface enabled service location by providing these 2 methods:

·         GetService(Type serviceType)

·         GetServices(Type serviceType)

While in MVC 2 a custom ControllerFactory has to be created (and specified in the application class), in MVC 3 all it takes is to specify a controller resolver.

This is example of the configuration of dependency injection configuration made in the application class (in the Application_Starts method), using Unity as the container library. (Unity for MVC 3 can be obtain from a NuGet package)

img

The following is the link of the Unity for MVC 3 project. Link

 

Comments

Leave a comment

 
 
 
 
CAPTCHA Image Validation