之前Ninject依赖注入是在MVC中使用,最近在WebApi中使用,用之前的MVC方式发现使用接口注入,一直是Null错误,网上查询了一些资源,总结一下,以后备用。
主要分为以下几步骤:
在NuGet上安装Ninject.MVC ,我安装的是最新版本nuget上安装Ninject.MVC5
定义两个类NinjectScope、NinjectResolver,用于实现最新版Web Api要求的IDependencyResolver
在Global中添加如下代码
protected void Application_Start()
{
//设置ApiController注入
GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(CreateKernel());
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
/// <summary>
/// 接口映射
/// </summary>
/// <returns></returns>
public IKernel CreateKernel()
{
var Kernel = new StandardKernel();
Kernel.Bind<IUser>().To<User>();
return Kernel;
}
4、在使用的地方,按照如下调用即可
public class StudentController : ApiController
{
[Ninject.Inject]
public IResource resource { get; set; }
[Ninject.Inject]
public IUser user { get; set; }
[HttpPost]
[AllowAnonymous]
public object Login([FromBody] UserModel model)
{
var model = user.GetLogin(model.UserCode, EncryptPwd, sysRole);
}
}
public class NinjectScope: IDependencyScope
{
protected IResolutionRoot
resolutionRoot;
public NinjectScope(IResolutionRoot
kernel)
{
resolutionRoot
= kernel;
}
public object GetService(Type
serviceType)
{
IRequest
request = resolutionRoot.CreateRequest(serviceType, null,
new Parameter[0],
true,
true);
return resolutionRoot.Resolve(request).SingleOrDefault();
}
public IEnumerable<object>
GetServices(Type serviceType)
{
IRequest
request = resolutionRoot.CreateRequest(serviceType, null,
new Parameter[0],
true,
true);
return resolutionRoot.Resolve(request).ToList();
}
public void Dispose()
{
IDisposable
disposable = (IDisposable)resolutionRoot;
if (disposable
!= null)
disposable.Dispose();
resolutionRoot
= null;
}
}
复制代码
public class NinjectResolver
: NinjectScope, IDependencyResolver
{
private IKernel
_kernel;
public NinjectResolver(IKernel
kernel)
:
base(kernel)
{
_kernel
= kernel;
}
public IDependencyScope
BeginScope()
{
return new NinjectScope(_kernel.BeginBlock());
}
}
软件定制,博远电子,友情提醒。
来源:抚顺市博远电子,如涉及版权问题请与我们联系。
TAG
软件定制,软件开发,瀚森HANSEN,辽宁,沈阳,抚顺