Unity Dependency Injection Container and ASP.NET MVC Framework
by David Hayden, Florida ASP.NET Developer
Update 2/14/2008: Added a Part II: ASP.NET MVC Framework and Unity Dependency Injection Container Part II
Update 2/19/2008: Added Unity IoC Dependency Injection and ASP.NET Model-View-Presenter
Update 2/22/2008: Added Unity Dependency Injection IoC Screencast
I couldn't resist trying one thing with Unity this morning before doing real work :) I wanted to try Unity with the ASP.NET MVC Framework for dependency injection into Controllers using a custom IControllerFactory.
I won't go into the Custom ControllerFactory in detail, but I did want to point out one cool thing about Unity in the sample code below:
public class CustomControllerFactory : IControllerFactory
{
public IController CreateController
(RequestContext context, Type controllerType)
{
IContainerAccessor containerAccessor =
context.HttpContext.ApplicationInstance
as IContainerAccessor;
return containerAccessor.Container.Get(controllerType)
as IController;
}
}
I don't have to add the Controller Class to the UnityContainer in order to create an instance of the Controller with all of its dependencies! Sweet! This avoids the whole process of reflecting over the controllers in the ASP.NET MVC Application and adding them to the UnityContainer as you will see in other controller factories like the Windsor ControllerFactory on MVCContrib. With Unity, you don't have to add a type to the container to create it.
I tried this both with Property Setter Dependency Injection:
public class HomeController : Controller
{
[Dependency]
public INewsService NewsService { get; set; }
[ControllerAction]
public void Index()
{
List<News> currentNews = NewsService.GetNews();
RenderView("Index", currentNews);
}
}
and Contructor Injection:
public class HomeController : Controller
{
private INewsService _newsService;
public HomeController(INewsService newsService)
{
_newsService = newsService;
}
[ControllerAction]
public void Index()
{
List<News> currentNews = _newsService.GetNews();
RenderView("Index", currentNews);
}
}
With the NewsService being registered in the UnityContainer at startup:
Container.Register<INewsService, NewsService>();
If you haven't already, go and download the Unity Dependency Injection Container.
Recent ASP.NET MVC Tutorials:
Author: David Hayden, Sarasota Web Developer