C# MVC应用程序中的Ninject WebApi问题
我目前有一个工作的MVC5应用程序,它使用Ninject进行依赖注入。 我现在已经习惯于在这个项目中添加一些WebAPI控制器,我想在它们中使用依赖注入 我读过几篇博客文章,了解到WebApi DI机制不同于MVC机制 为此,我创建了一个新的DependencyResolver用于WebApi,如下所示:C# MVC应用程序中的Ninject WebApi问题,c#,asp.net-mvc,asp.net-web-api,dependency-injection,ninject,C#,Asp.net Mvc,Asp.net Web Api,Dependency Injection,Ninject,我目前有一个工作的MVC5应用程序,它使用Ninject进行依赖注入。 我现在已经习惯于在这个项目中添加一些WebAPI控制器,我想在它们中使用依赖注入 我读过几篇博客文章,了解到WebApi DI机制不同于MVC机制 为此,我创建了一个新的DependencyResolver用于WebApi,如下所示: public class NinjectWebApiDependencyResolver : NinjectDependencyScope, System.Web.Http.Depen
public class NinjectWebApiDependencyResolver : NinjectDependencyScope,
System.Web.Http.Dependencies.IDependencyResolver
{
private readonly IKernel _kernel;
public NinjectWebApiDependencyResolver(IKernel kernel)
: base(kernel)
{
this._kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(_kernel.BeginBlock());
}
}
我的MVC DependencyResolver如下所示:
public class NinjectMvcDependencyResolver : NinjectDependencyScope,
System.Web.Mvc.IDependencyResolver
{
#region Fields
private readonly IKernel kernel;
#endregion
#region Constructors and Destructors
public NinjectMvcDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
#endregion
#region Public Methods and Operators
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
#endregion
}
我使用以下代码在NinjectWebCommon.cs中注册两个解析器:
var resolver = new NinjectMvcDependencyResolver(kernel);
// Install into the MVC dependency resolver
DependencyResolver.SetResolver(resolver);
// Install the WebApi Dependency resolver
GlobalConfiguration.Configuration.DependencyResolver = new NinjectWebApiDependencyResolver(kernel);
这一切似乎都很好,在向Api控制器发出第一个请求时,DI工作,但在后续调用中,它失败并出现错误:
中发生“System.InvalidOperationException”类型的异常
Ninject.dll,但未在用户代码中处理
Additional information: Error loading Ninject component ICache
No such component has been registered in the kernel's component container.
Suggestions:
1) If you have created a custom subclass for KernelBase, ensure that you have properly
implemented the AddComponents() method.
2) Ensure that you have not removed the component from the container via a call to RemoveAll().
3) Ensure you have not accidentally created more than one kernel.
有人知道为什么吗?我知道上述原因都不是失败的原因
PS:我已经研究了以下解决方案,但它也不适用于我:
您是否使用Ninject为DI提供的NuGet软件包?还有?只有Ninject.Web.Mvc一个。因此Ninject.Web.WebApi NuGet值得一看-它内置了
IDependencyResolver
,可以配置为共享Mvc项目使用的内核。。。我怀疑您的BeginScope
实现中出现了一些“奇怪”的情况