This post has been migrated from www.experimentsincode.com, we apologise if some of the images or content is missing

The post has been migrated, original date 20 May 2009. Your controllers in the MVC pattern are going to need access to service classes, rather than instantiate a concrete version of the service class in a controller it would be better to inject the services we needed into the controller. Firstly we need to ensure that the constructor of the controller has the interface of the service we want to use:
    public class BlogController : Controller
    {
        private IBlogRepository _blogRespository;

        public BlogController(IBlogRepository blogRespository)
        {
            _blogRespository = blogRespository;
        }
    }
The default controller factory System.Web.Mvc.DefaultControllerFactory requires all controllers to have a parameterless constructor, so we have to create another controller factory. This factory will get the type of controller we want and then use a Windsor container to create a concrete version of it:
    public class WindsorControllerFactory : DefaultControllerFactory
    {

        #region IControllerFactory Members

        public override  IController CreateController(RequestContext requestContext, string controllerName)
        {
	    IWindsorContainer container = new WindsorContainer(new XmlInterpreter());
            Type controllerType = this.GetControllerType(controllerName);
            _container.AddComponent(controllerName, controllerType);
            return (IController) container.Resolve(controllerType);
        }

        #endregion
    }
By inheriting from from the DefaultControllerFactory we can get it to do all the work of actually working out which type of controller we wanted. We then have to add the new controller to the Windsor container so that it is aware of the controller (this saves us configuring each controller in the config file), next the type is passed to Windsor to create a concrete version.
comments powered by Disqus