DCSIMG
How To Use Unity Container In ASP.NET MVC Framework - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2011 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

How To Use Unity Container In ASP.NET MVC Framework

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

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# February 8, 2009 3:54 PM

Rotem Bloom said:

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

# February 8, 2009 8:28 PM

How To Use Unity Container In ASP.NET MVC Framework - Gil Fink on .Net said:

Pingback from  How To Use Unity Container In ASP.NET MVC Framework - Gil Fink on .Net

# February 8, 2009 9:00 PM

ASP.NET MVC Archived Blog Posts, Page 1 said:

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

# February 9, 2009 6:24 AM

Dew Drop - February 9, 2009 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop - February 9, 2009 | Alvin Ashcraft's Morning Dew

# February 9, 2009 4:20 PM

Tiit said:

Thank You very much, just what i needed;)

# February 10, 2009 2:34 PM

Gil Fink said:

Happy to help Tiit.

# February 10, 2009 3:31 PM

Unity IoC and MVC 3 Beta – Passing IRepository to Controller Constructor | DeveloperQuestion.com said:

Pingback from  Unity IoC and MVC 3 Beta &#8211; Passing IRepository to Controller Constructor | DeveloperQuestion.com

# October 17, 2010 1:12 AM

Gil Fink on .Net said:

Dependency Injection in MVC 3 Was Made Easier In the past I wrote a post that showed how to implement

# October 17, 2010 11:26 AM

Dependency Injection « Code Barn said:

Pingback from  Dependency Injection &laquo; Code Barn

# March 4, 2011 7:56 PM