#region License // // Authors: Nate Kohari , Josh Close // Copyright (c) 2007-2009, Enkari, Ltd. // // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). // See the file LICENSE.txt for details. // #endregion #region Using Directives using System; using System.Diagnostics; using System.Web.Mvc; using System.Web.Routing; #endregion namespace Ninject.Web.Mvc { /// /// A controller factory that creates s via Ninject. /// public class NinjectControllerFactory : DefaultControllerFactory { /// /// Gets the kernel that will be used to create controllers. /// public IKernel Kernel { get; private set; } /// /// Initializes a new instance of the class. /// /// The kernel that should be used to create controllers. public NinjectControllerFactory(IKernel kernel) { Kernel = kernel; } /// /// Gets a controller instance of type controllerType. /// /// The request context. /// Type of controller to create. /// The controller instance. protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { // let the base handle 404 errors with proper culture information return base.GetControllerInstance(requestContext, controllerType); } var controller = Kernel.GetService(controllerType) as IController; if (controller == null) return base.GetControllerInstance(requestContext, controllerType); var standardController = controller as Controller; if (standardController != null) standardController.ActionInvoker = CreateActionInvoker(); return controller; } /// /// Creates the action invoker. /// /// The action invoker. protected virtual NinjectActionInvoker CreateActionInvoker() { return new NinjectActionInvoker(Kernel); } } }