MVC4中使用Ninject

MVC4中使用Ninject

1.NuGet获取Ninject.dll

 

 

MVC4中使用Ninject_第1张图片MVC4中使用Ninject_第2张图片

 

 

.NET技术交流群 199281001 .欢迎加入。

 

 

2.全局注册  Global.asax.cs

  RegisterNinject
//注册Ninject依赖注入全局解析器
2  GlobalConfiguration.Configuration.DependencyResolver = new System.Web.Http.Dependencies.NinjectDependencyResolver(new Ninject.StandardKernel());

 

3.辅助类

  NinjectDependencyResolver
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 }

 

  NinjectDependencyScope

using Ninject.Activation;
using Ninject.Parameters;
using Ninject.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;

namespace System.Web.Http.Dependencies
{
//Author:GaoBingBing
public class NinjectDependencyScope : IDependencyScope
{
protected IResolutionRoot resolutionRoot;
public NinjectDependencyScope()
{

}
public NinjectDependencyScope(IResolutionRoot resolutionRoot)
{
this.resolutionRoot = resolutionRoot;
}
public object GetService(Type serviceType)
{
return resolutionRoot.Resolve(this.CreateRequest(serviceType)).SingleOrDefault();
}

public IEnumerable<object> GetServices(Type serviceType)
{
return this.resolutionRoot.Resolve(this.CreateRequest(serviceType));
}
private IRequest CreateRequest(Type serviceType)
{
return resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
}
public void Dispose()
{
this.resolutionRoot = null;
}
}
}

NinjectDependencyScope

4.Config

  DIConfig

//Author:GaoBingBing
public class DIConfig
{
public static T CreateInstance<T>() where T : class
{
System.Web.Http.Dependencies.IDependencyResolver resolver = System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver;
return resolver.BeginScope().GetService(typeof(T)) as T;
}

}

DIConfig


5.调用

private IXX   _x=DIConfig.CreateInstance<IXX>();



6.谢谢关注

 

 
 
分类:  ASP.NETASP.NET MVC 4C#IOC

你可能感兴趣的:(inject)