May 24, 2012

Custom Controller Factory

Constructor Injection is the DI technique of passing an object's dependencies to its constructor. But this by default will not work with Mvc unless you have a parameterless constructor also defined. If you try to run, it will throw error stating that “No parameterless constructor is defined for this object”. A way to get around this and have DI is by defining both parameterless constructor as well as one with which you want to have dependency.

public class ProductController : Controller
    {
        #region Constructor
        
        public ProductController()
            : this(new ProductModel())
        {
        }

        public ProductController(IProductModel productModel)
        {
            if (productModel == null)
                throw new ArgumentNullException("productModel");
            ProductModel = productModel;
        }

        private IProductModel ProductModel { get; set; } 

        #endregion

The other way to achieve this is by defining CustomeControllerFactoryWithoutDefaultConstructor something like this

public class CustomeControllerFactoryWithoutDefaultConstructor : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            return Activator.CreateInstance(controllerType, new ProductModel()) as IController;
        }
    }

And then register this in Global.asax:

ControllerBuilder.Current.SetControllerFactory(typeof(CustomeControllerFactoryWithoutDefaultConstructor));

No comments:

Post a Comment