How To Use Unity Container In ASP.NET MVC Framework

February 8, 2009

How To Use Unity Container In ASP.NET MVC Framework


In the past I wrote theHow To Use Unity Container In ASP.NET MVC Framework
post How To Use Unity
Container In ASP.NET
.
In this post I’m going to
explain how we can 
use Unity IoC container
in ASP.NET MVC Framework.


Building The Container


As in the previous post the first thing to do is to build the
container itself. I’ll use the same method I used in the previous post 
in order to persist the Unity container’s state during the application
execution. The right place to put the Unity container is as part of the
Global.asax file as a property of the current running application.
I’m going to use the same interface as before:



public interface IContainerAccessor
{
    IUnityContainer Container { get; }
}

After the building of the interface implement it in the Global
class in the Global.asax file:



public class MvcApplication : HttpApplication, IContainerAccessor
{
    #region Members
 
    private static IUnityContainer _container;
 
    #endregion
 
    #region Properties
 
    /// <summary>
    /// The Unity container for the current application
    /// </summary>
    public static IUnityContainer Container
    {
        get
        {
            return _container;
        }
    }
 
    #endregion
 
    #region IContainerAccessor Members
 
    /// <summary>
    /// Returns the Unity container of the application 
    /// </summary>
    IUnityContainer IContainerAccessor.Container
    {
        get { return Container; }
    }
 
    #endregion
 
    #region Application Events
 
    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
        InitContainer();
        ControllerBuilder.Current.SetControllerFactory(typeof(UnityControllerFactory));
    }
 
    protected void Application_End(object sender, EventArgs e)
    {
        CleanUp();
    }
 
    #endregion
 
    #region Methods
 
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
 
        routes.MapRoute(
            “Default”,                                              // Route name
            “{controller}/{action}/{id}”,                           // URL with parameters
            new { controller = “Home”, action = “Index”, id = “” }  // Parameter defaults
        );
 
    }
 
    private static void InitContainer()
    {
        if (_container == null)
        {
            _container = new UnityContainer();
        }
 
        // Register the relevant types for the 
        // container here through classes or configuration
        _container.RegisterType<IMessageService, MessageService>();
    }
 
    private static void CleanUp()
    {
        if (Container != null)
        {
            Container.Dispose();
        }
    }
 
    #endregion
 
}

The Unity Controller Factory


The real and important change with this new implementation of
Global.asax is the setting of the controller factory which I wrote.
The code for the UnityControllerFactory:



public class UnityControllerFactory : IControllerFactory
{
    #region IControllerFactory Members
 
    public IController CreateController(RequestContext requestContext, string controllerName)
    {
        IContainerAccessor containerAccessor =
            requestContext.HttpContext.ApplicationInstance as IContainerAccessor;
 
        Assembly currentAssembly = Assembly.GetExecutingAssembly();
        var controllerTypes = from t in currentAssembly.GetTypes()
                              where t.Name.Contains(controllerName + “Controller”)
                              select t;
 
        if (controllerTypes.Count() > 0)
        {
            return containerAccessor.Container.Resolve(controllerTypes.First()) as IController;
        }
        else
        {
            return null;
        }
    }
 
    public void ReleaseController(IController controller)
    {
        controller = null;
    }
 
    #endregion
}

The main thing to do is to implement the CreateController method of
the IControllerFactory interface. I use the request context parameter to
retrieve the current application instance and from it I get the Unity container
through the interface of IContainerAccessor. I also need to instantiate the
relevant controller class which is being done by the Unity container for me.
The container will inject the dependencies in the controller by the Resolve
method and we will get the dependency injection functionality that we
wanted.


The Class to be Injected


I also wrote a MessageService which is a simple class that returns a
message and inherit from the IMessageService which declare the
GetMessage method:



public interface IMessageService
{
    string GetMessage();
}
 
public class MessageService : IMessageService
{
    #region IMessageService Members
 
    public string GetMessage()
    {
        return “Hello Controller!”;
    }
 
    #endregion
}

 


The Controller


The last piece of this puzzle is the controller class.
I implemented the HomeCotroller class with the following code:



[HandleError]
public class HomeController : Controller
{
    #region Members
 
    [Dependency]
    public IMessageService MessageService { get; set; }        
 
    #endregion
 
    #region Actions
 
    public ActionResult Index()
    {
        ViewData["Message"] = MessageService.GetMessage();
        return View();
    }
 
    public ActionResult About()
    {
        return View();
    }
 
    #endregion
}

 


The UnityControllerFactory will inject the dependency of the MessageService
property with the relevant class and that’s it simple as that.


Summary


Lets sum up, I showed an example of how to use Unity container in ASP.NET
MVC Framework application. This is a very simple example that will help you
to get started with Unity in your MVC web applications


DotNetKicks Image

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

3 comments

  1. Rotem BloomFebruary 8, 2009 ב 20:28

    Microsoft PRISM framework use the Unity framework a lot. You can find a lot of examples on this framework.

    Reply
  2. TiitFebruary 10, 2009 ב 14:34

    Thank You very much, just what i needed;)

    Reply