Unity Controller Factory for MVC 2

May 12, 2010 at 1:15 AM

Hey all,

I've created a simple Unity Controller Factory that you can use to resolve controllers in MVC applications.  The class looks like:

public class UnityControllerFactory : DefaultControllerFactory
    {
        private IUnityContainer _Container;
        
        public UnityControllerFactory()
        {
            // Instantiate a container, taking configuration from unity.config
            _Container = new UnityContainer().LoadConfiguration();
        }

        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            IController controller;

            if (controllerType == null)
            {
                throw new HttpException(404, string.Format("The controller for path '{0}' could not be found or it does not implement IController.", requestContext.HttpContext.Request.Path));
            }
            else
            {
                controller = _Container.Resolve(controllerType) as IController;
            }

            return controller;
        }
    }

This can be implented into an MVC application by editing the Application_Start() section of the Global.asax.cs:

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory());
        }

What are your thoughts on this?  Anyone have a different implementation?