Dependency in MVC2

Idea from this post.
By default, MVC2 can’t handle ctor injection.

    [HandleError]
    public class HomeController : Controller
    {
        private readonly IGreatingService _greatingService;

        public HomeController(IGreatingService greatingService)
        {
            _greatingService = greatingService;
        }

        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!" + _greatingService.SayHello();

            return View();
        }
}

Solution: A custom ControllerFactroy can be set in App_start.


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

            RegisterRoutes(RouteTable.Routes);

            ControllerBuilder.Current.SetControllerFactory(IoC.GetControllerFactory());
        }

   public static class IoC
    {
        public static IKernel Kernel;

        static IoC()
        {
//            ObjectFactory.Initialize(x => x.AddRegistry(new ControllerDependencyRegistry()));
            Kernel = new StandardKernel(new ControllerModule());
        }

        public static IControllerFactory GetControllerFactory()
        {
            return new ControllerFactory();
        }

        public static object Get(Type type)
        {
//            return ObjectFactory.GetInstance(type);
            return Kernel.Get(type);
        }
    }

    public class ControllerFactory : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                return base.GetControllerInstance(requestContext, controllerType);
            }

            return IoC.Get(controllerType) as Controller;
        }
    }

    //  Ninject implementation
    public class ControllerModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IGreatingService>().To<GreatingService>();
        }
    }

    // StructureMap implementation
    public class ControllerDependencyRegistry : Registry
    {
        public ControllerDependencyRegistry()
        {
            For<IGreatingService>().Use<GreatingService>();
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s