标签:style blog http color 使用 os
1.NuGet获取Ninject.dll
.NET技术交流群 199281001 .欢迎加入。
2.全局注册 Global.asax.cs
1 //注册Ninject依赖注入全局解析器 2 GlobalConfiguration.Configuration.DependencyResolver = new System.Web.Http.Dependencies.NinjectDependencyResolver(new Ninject.StandardKernel());
3.辅助类
1 using BLL; 2 using IBLL; 3 using Ninject; 4 using System.Web.Http.Dependencies; 5 6 namespace System.Web.Http.Dependencies 7 { 8 //Author:GaoBingBing 9 public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver 10 { 11 [Ninject.Inject] 12 private IKernel kernel; 13 public NinjectDependencyResolver() 14 { 15 16 } 17 public NinjectDependencyResolver(IKernel kernel) 18 { 19 this.kernel = kernel; 20 this.kernel.Settings.InjectNonPublic = true; 21 this.AddBinds(); 22 } 23 24 private void AddBinds() 25 { 26 27 //由此添加你的注入 28 this.kernel.Bind<IXX>().To<XX>(); 29 } 30 //开始处理 31 public IDependencyScope BeginScope() 32 { 33 return new NinjectDependencyScope(this.kernel.BeginBlock()); 34 } 35 36 37 38 } 39 }
1 using Ninject.Activation; 2 using Ninject.Parameters; 3 using Ninject.Syntax; 4 using System; 5 using System.Collections.Generic; 6 using System.Linq; 7 using System.Web.Http.Dependencies; 8 9 namespace System.Web.Http.Dependencies 10 { 11 //Author:GaoBingBing 12 public class NinjectDependencyScope : IDependencyScope 13 { 14 protected IResolutionRoot resolutionRoot; 15 public NinjectDependencyScope() 16 { 17 18 } 19 public NinjectDependencyScope(IResolutionRoot resolutionRoot) 20 { 21 this.resolutionRoot = resolutionRoot; 22 } 23 public object GetService(Type serviceType) 24 { 25 return resolutionRoot.Resolve(this.CreateRequest(serviceType)).SingleOrDefault(); 26 } 27 28 public IEnumerable<object> GetServices(Type serviceType) 29 { 30 return this.resolutionRoot.Resolve(this.CreateRequest(serviceType)); 31 } 32 private IRequest CreateRequest(Type serviceType) 33 { 34 return resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true); 35 } 36 public void Dispose() 37 { 38 this.resolutionRoot = null; 39 } 40 } 41 }
4.Config
1 //Author:GaoBingBing 2 public class DIConfig 3 { 4 public static T CreateInstance<T>() where T : class 5 { 6 System.Web.Http.Dependencies.IDependencyResolver resolver = System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver; 7 return resolver.BeginScope().GetService(typeof(T)) as T; 8 } 9 10 }
5.调用
private IXX _x=DIConfig.CreateInstance<IXX>();
6.谢谢关注
ASP.NET MVC4中使用Ninject,布布扣,bubuko.com
标签:style blog http color 使用 os
原文地址:http://www.cnblogs.com/gaobing/p/3809551.html