Alternative to using deprecated Kernel attribute? (MVC)

98 views
Skip to first unread message

Kevin Major

unread,
Jul 15, 2012, 9:30:35 PM7/15/12
to nin...@googlegroups.com
In my MVC projects, I derive my controllers from a custom base controller in order to better handle situations that would necessitate me to return a 404 or 500 status code.  In order to do that, I have my own controller factory that is invoked in OnApplicationStartred().  The only problem is that it requires the Ninject kernel to work, and I can only seem to get it via the deprecated attribute.  Code:

HGControllerFactory:

    public class HGControllerFactory : IControllerFactory
    {
        private IControllerFactory defaultFactory;
        private IKernel kernel;
 
        public HGControllerFactory(IControllerFactory defaultFactory, IKernel kernel)
        {
            this.defaultFactory = defaultFactory;
            this.kernel = kernel;
        }
 
        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            try
            {
                var controller = defaultFactory.CreateController(requestContext, controllerName);
                return controller;
            }
            catch (HttpException ex)
            {
                // Pasted in your exception handling code here:
                if (ex.GetHttpCode() == 404)
                {
                    IController errorController = kernel.Get<ErrorController>();
                    ((ErrorController)errorController).InvokeHttp404(requestContext.HttpContext);
 
                    return errorController;
                }
                else
                {
                    throw ex;
                }
            }
        }
 
        public void ReleaseController(IController controller)
        {
            defaultFactory.ReleaseController(controller);
        }
}


OnApplicationStarted():

        protected override void OnApplicationStarted()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
            ControllerBuilder.Current.SetControllerFactory(new HGControllerFactory(ControllerBuilder.Current.GetControllerFactory(), this.Kernel));
        }


Is there another way for me to get a hold of the Ninject kernel?

Remo Gloor

unread,
Jul 19, 2012, 8:40:53 AM7/19/12
to nin...@googlegroups.com
Ninject.MVC3 isn't designed to work with a custom controller factory.

Alternatively you can implement Application_Error() in your global.asax (or a HttpApplication.Error eventhandler in a IHttpModule, in case you need dependencies) and redirect to the appropriate error controller. See http://stackoverflow.com/a/5229581/448580 for an example.

Kevin Major

unread,
Jul 20, 2012, 10:57:20 AM7/20/12
to nin...@googlegroups.com
Ah, excellent.  Thank you.
Reply all
Reply to author
Forward
0 new messages