MVC UnityControllerFactory resolve multiple level dependencys passing down a parameter.

Mar 26, 2011 at 5:45 PM

I am trying to use Unity to create Controllers for me in my MVC application.

My problem is (due to a funny database design and lots of legacy code) that I need to pass a long into the constructor of the majority of my repositories.  This long value will only be known at runtime.

I have started writting code to implement Unity in the root of the MVC applicaiton outlined as follows.

 public class MvcApplication : HttpApplication
        protected void Application_Start()

        private static void ConfigureUnity()
            IUnityContainer container = new UnityContainer();


            ControllerBuilder.Current.SetControllerFactory(new DIFactory(container));

        private static void RegisterInstances(IUnityContainer container)
            #region Repositories

                new ClientRepository(Parameter));

            #endregion Repositories

            #region Controlers

                new PivotClientController(container.Resolve<IClientRepository>()));

            #endregion Controlers

        public class DIFactory : DefaultControllerFactory
            IUnityContainer container;

            public DIFactory(IUnityContainer container)
                this.container = container;

            protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType)
                return controller = container.Resolve(controllerType) as IController;
So to create an instance of my PivotClientController class I am asking Unity to get me an instance of ClientRepository into which I need to pass a value ('Parameter' in the code above) that will only be known at run time.
Is it possible to pass to accomplish this?
I have been looking at container.Resolve<IFoo>(new ParameterOverrides<Foo> { { "name", "bar" }, { "address", 42 } }) but as I need to resolve with a Type variable this doesn't seem possible to use.
Confussed :S
Mar 27, 2011 at 12:47 PM

You can make use of ParameterOverride regardless if you can't make use of the generic Resolve method:

container.Resolve(controllerType, new ParameterOverride("name", "bar"), new ParameterOverride("address", 42));


Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.