ASP.NET MVC4 - Setting up Dependency Injection (Unity)

by BillKrat 16. October 2011 05:40

Click here for primer on Dependency Injection

Note: See changeset 93638 on http://SolrContrib.CodePlex.com documentation tab for referenced source code below

My http://SolrContrib.CodePlex.com  application will evolve (in an Agile way) to a data driven application (for Desktop, Silverlight and Phone).   For our web application, ASP.NET MVC4 is a perfect choice - it will make the process simple, i.e., with the simple registration on line 23 below, my CustomController will now handle admin request such as http://iso15926.global-webnet.com/browser/admin (which is not currently plugged in yet).

Fortunately, Brad Willson has a good series (MVC3) which helped me get ramped up pretty quick - it is available at
http://bradwilson.typepad.com/blog/2010/07/service-location-pt2-controllers.html.   I did make some minor modifications to support an IBuildUp interface.  What this does is provide Dependency Injection (DI) support for "all" controllers, not just registered controllers as in the case above.  

I wanted to ensure backwards compatability so that no additional coding is required for standard controllers.  For controllers that do require DI  all that is required is to implement IBuildUp on controller and the UnityControllerFactory will take care of the rest. 

 

Below is an example of what our GlossaryController looks like, it derives from GwnControllerBase which implements IBuildUp.  Referencing the above code it becomes apparent how I can now RegisterTypes, such as my Business Logic and Data Access Layer implementation, and use the Intialize method to retrieve the data that will drive my View (via ContentModelList) 

The resulting output follows http://iso15926.global-webnet.com/browser/Glossary.  This permits me to easily add pages by simply updating my data access layer (hard coded for now).  Later I can beef up the glossary display but for now it is functional.

UC0000-0000-010-010-010-AspMvc Controllers

Notice

Hall of fame

Blog videos and references to CodePlex projects are no longer valid