标签:
ninject是一个轻量级的依赖注入在性能上不及spring,castle的依赖注入但在一般的项目中还是能满足需求的,话不所说看看怎么用吧!
首先在nuget上下载安装包:
新建一个mvc项目:
在项目中新建一个NinjectWebComment类,在类中添加下列代码:
public static class NinjectWebCommon { private static readonly Bootstrapper bootstrapper = new Bootstrapper(); /// <summary> /// Starts the application /// </summary> public static void Start() { DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); bootstrapper.Initialize(CreateKernel); } /// <summary> /// Stops the application. /// </summary> public static void Stop() { bootstrapper.ShutDown(); } /// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(); try { kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel); return kernel; } catch { kernel.Dispose(); throw; } } /// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { } }
然后在global.asax中注册控制器工厂:
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
一个可依赖注入项目就成功了;
标签:
原文地址:http://www.cnblogs.com/lishuhua/p/4766617.html