1.NuGet获取Ninject.dll
选中项目右键:
.NET技术交流群 199281001 .欢迎加入。
2.全局注册 Global.asax.cs
//注册Ninject依赖注入全局解析器
GlobalConfiguration.Configuration.DependencyResolver = new System.Web.Http.Dependencies.NinjectDependencyResolver(new Ninject.StandardKernel());
RegisterNinject
3.辅助类
using BLL;
using IBLL;
using Ninject;
using System.Web.Http.Dependencies; namespace System.Web.Http.Dependencies
{
//Author:GaoBingBing
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
[Ninject.Inject]
private IKernel kernel;
public NinjectDependencyResolver()
{ }
public NinjectDependencyResolver(IKernel kernel)
{
this.kernel = kernel;
this.kernel.Settings.InjectNonPublic = true;
this.AddBinds();
} private void AddBinds()
{ //由此添加你的注入
this.kernel.Bind<IXX>().To<XX>();
}
//开始处理
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(this.kernel.BeginBlock());
} }
}
NinjectDependencyResolver
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[], true, true);
}
public void Dispose()
{
this.resolutionRoot = null;
}
}
}
NinjectDependencyScope
4.Config
//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.谢谢关注
作者:gaobing
提示:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。