One of the new features of ASP.NET MVC3 is better support for dependency injection. There are changes in how the framework interacts with your Inversion of Control (IoC) Container.
As we all know the whole point of DI is about separating component behavior from dependency resolution without object intervention. DI is a particular implementation of Inversion of Control, where the consumer object receives his dependencies inside constructor properties or arguments. DI requires a framework component behind to deal with class constructor.
The web is full of blog posts on Dependency Injection and IoC. However – this post is aimed at providing a very basic example of a custom DependencyResolver with a Property Injection to HomeController.
I have setup the HomeController with a property WelcomeMessage.
In the Global.aspx, I have registered a SimpleDependencyResolver which essentially implements IDependencyResolver as depicted below. The point to note here is the default values I am giving as part of the GetService() method. This example is based on Maarten Balliauw's session on ASP.NET MVC3 and MEF @ MIX11
Register the DependencyResolver at Application_Start() as below:
The Class Definition is as below:
Now run the code and see the DI in action in its simplest form.
Interesting subject but stop reading it when saw how unreadable code sections are. Use some code formatting tool/extension
Thanks for the comment. I have modified the code sections with QuickHighlighter which makes it more readable now. You own a real thanks since I got introduced to a new online tool which I can use for my blogs posts going forward.