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..
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.
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.
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.
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.
Source code could be downloaded from here.