Oxite Administrator (gravatar)

Dependency Injection in Asp.net MVC using MVC Contrib

For the sake of creating the sample let's introduce the dependency of a ILinkRepository in our brand new asp.net MVC application. Eventually this repository will be used by our HomeController to display a number of Links and finally we will inject the dependency by StructureMap dependency framework.. 

Hosted by imgur.com

Next we will add the dependency of ILinkRepository on our HomeController. Since the default ControllerFactory cannot cope with controllers having no default constructor we will hard code the initialization of this dependency on the default constructor. Finally we will pass the list of links to the view and the view will display it for the user. This is the common scenario.

Hosted by imgur.com

Since view is strongly typed, it will just iterate over the collection producing a list of links. We are now done with the basic structure of the application. We have just used a type of dependency injection infamously known as Poor Man's dependency injection since the HomeController constructor hard coded the creation of the repository.

Hosted by imgur.com

Now, it's time to modify the controller for dependency injection. Since we are using dependency injection, controller is not concerned with creating the repository as in previous version. Dependency injection framework will automatically provide the dependent repository to the controller. 

Hosted by imgur.com

Running the application now will definitely produce an error since the default controller factory cannot create controllers having no parameterless constructor as shown below. 

No parameterless constructor defined for this object.

Finally we are in a position to introduce the StructureMap dependency injection framework to the MVC application. It could be configured in the Global.asax.cs file as follows and the application will run as expected.

Hosted by imgur.com

 

Source code could be downloaded from here.

 

Shout it

1 Comment

  • Fernando (gravatar)

    Fernando said
    February 19, 2010

    Hello,

    I used the above mechanism to successfully inject repositories.
    Unfortunately, I was not able to inject webservices. Is there any kind of limitation towards that kind of injection?

    Thank you

Your Information
Mrs. Gravatar (gravatar)

<-- It's a gravatar

your comment