Last active
August 29, 2015 13:56
-
-
Save spewu/8802209 to your computer and use it in GitHub Desktop.
Example Ninject configuration for an ASP.NET MVC application. I use a custom ControllerFactory only to get better exception messages if a Ninject binding is not configured properly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In Global.asax, in Application_Start make a call to NinjectContainer.Register(...); providing the NinjectModules to configure | |
namespace Test | |
{ | |
using System; | |
using System.Collections.Generic; | |
using System.Web.Mvc; | |
using System.Web.Routing; | |
using Ninject; | |
using Ninject.Modules; | |
public class NinjectDependencyResolver : IDependencyResolver | |
{ | |
public NinjectDependencyResolver(IKernel kernel) | |
{ | |
Kernel = kernel; | |
} | |
public NinjectDependencyResolver(params INinjectModule[] modules) | |
{ | |
Kernel = new StandardKernel(modules); | |
} | |
public IKernel Kernel { get; private set; } | |
public object GetService(Type serviceType) | |
{ | |
return Kernel.TryGet(serviceType); | |
} | |
public IEnumerable<object> GetServices(Type serviceType) | |
{ | |
return Kernel.GetAll(serviceType); | |
} | |
} | |
public class NinjectControllerFactory : DefaultControllerFactory | |
{ | |
private readonly NinjectDependencyResolver resolver; | |
public NinjectControllerFactory(NinjectDependencyResolver resolver) | |
{ | |
this.resolver = resolver; | |
} | |
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) | |
{ | |
return (controllerType == null) ? null : (IController)resolver.Kernel.Get(controllerType); | |
} | |
} | |
public class NinjectContainer | |
{ | |
public static void Register(IKernel kernel) | |
{ | |
Register(new NinjectDependencyResolver(kernel)); | |
} | |
public static void Register(INinjectModule[] modules) | |
{ | |
Register(new NinjectDependencyResolver(modules)); | |
} | |
public static void Register(NinjectDependencyResolver ninjectDependencyResolver) | |
{ | |
DependencyResolver.SetResolver(ninjectDependencyResolver); | |
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(ninjectDependencyResolver)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment