我最近将 Ninject 和 Ninject.Web.Mvc 添加到现有的 ASP.NET MVC 4 Web 应用程序中。浏览网站时,我收到以下异常,似乎是随机的:
[InvalidOperationException: 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. ] Ninject.Components.ComponentContainer.Get(Type component) in c:\Projects\Ninject\ninject\src\Ninject\Components\ComponentContainer.cs:160 Ninject.Components.ComponentContainer.Get() in c:\Projects\Ninject\ninject\src\Ninject\Components\ComponentContainer.cs:116 Ninject.Web.Common.<>c__DisplayClass2.b__1(IKernel kernel) in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\OnePerRequestHttpModule.cs:74 Ninject.GlobalKernelRegistration.MapKernels(Action`1 action) in c:\Projects\Ninject\ninject\src\Ninject\GlobalKernelRegistration.cs:75 Ninject.Web.Common.OnePerRequestHttpModule.DeactivateInstancesForCurrentHttpRequest() in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\OnePerRequestHttpModule.cs:74 Ninject.Web.Common.OnePerRequestHttpModule.b__0(Object o, EventArgs e) in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\OnePerRequestHttpModule.cs:56 System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
一旦我收到上述异常,只需刷新或单击返回似乎就会导致网站再次开始正常运行。该网站的任何一个区域似乎都不会比另一个区域更容易导致这种情况发生。
该问题与此处提出的问题非常相似:Ninject + "Error loading Ninject component ICache" 。然而,该问题中的问题似乎是由扩展本身的错误引起的,已经存在一年多了,并且看起来已经解决。
发生这种情况时无需对 NinjectWebCommon.cs 文件进行任何修改。 (没有加载模块,没有添加绑定(bind)。)我让它停止的唯一方法是从项目中完全排除 NinjectWebCommon.cs 。
我不确定要包含哪些其他信息,因为除了安装 Nuget 软件包之外我几乎没有做任何事情。也许值得注意的是,该项目确实包含对利用 Ninject 进行 DI 的其他程序集的引用。
我环顾四周,不明白为什么会发生这种情况。任何建议将不胜感激。
最佳答案
显然,您的应用程序中涉及多个内核(MVC + Lib)。在应用程序运行时创建和处置内核实例是应该避免的。我强烈建议更改您的设计,以便在应用程序启动时创建尽可能少的内核。稍后不会创建任何内容(包括所有库)。
话虽如此,我在代码中没有看到最新版本的 Ninject 会如何发生此问题。可能值得验证应用程序和所有库是否都在最新版本的 Ninject 上。
关于asp.net-mvc - 随机发生的 Ninject 异常 : "Error loading Ninject component ICache",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13732645/