加载Ninject组件ICache时出错

加载Ninject组件ICache时出错

本文介绍了Ninject +“加载Ninject组件ICache时出错”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚从NuGet安装了新的Ninject.MVC3,并试图使其在我的asp.net mvc 3应用程序中工作,但是我现在得到这个奇怪的错误,然后在冲浪我的网站时:

  [InvalidOperationException:加载Ninject组件时遇到错误ICache 
没有这样的组件已经在内核的组件容器中注册。

建议:
1)如果您为KernelBase创建了一个自定义子类,请确保您已正确使用
实现了AddComponents()方法。
2)确保您没有通过调用RemoveAll()从容器中删除组件。
3)确保您没有意外创建多个内核。
]
Ninject.Components.ComponentContainer.Get(类型组件)在d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\Components\ComponentContainer.cs:146
Ninject.Components.ComponentContainer.Get()在d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\Components\ComponentContainer.cs:102
Ninject.KernelBase在d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\KernelBase.cs中的.CreateContext(IRequest请求,IBinding绑定):540
Ninject。c__DisplayClassa。<在d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\KernelBase.cs中解析> b__6(IBinding binding):375
System.Linq。c__DisplayClass12`3。 < CombineSelectors> b__11(TSource x)+20
System.Linq.WhereSelectEnumerableIterator`2.MoveNext()+151
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source)+4178557
Ninject.Web.Mvc。 C:\Projects\Ninject\\\
inject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectDependencyResolver.cs中的NinjectDependencyResolver.GetService(键入serviceType):56
System.Web .Mvc.DefaultControllerActivator.Create(RequestContext requestContext,Type controllerType)+51

[InvalidOperationException:尝试创建类型为MyApp.Controllers.NewsController的控制器时出错。确保控制器有一个无参数的公共构造函数。]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext,Type controllerType)+182
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext ,类型controllerType)+80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext,String controllerName)+74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext,IController& controller,IControllerFactory& ; factory)+196
System.Web.Mvc。c__DisplayClass6。< BeginProcessRequest> b__2()+49
System.Web.Mvc。c__DisplayClassb`1。< ProcessInApplicationTrust> b__a()+13
System.Web.Mvc.SecurityUtil。< GetCallInAppTrustThunk> b__0(Action f)+7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action)+22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 fun c)+124
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext,AsyncCallback callback,Object state)+98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,AsyncCallback callback,Object状态)+50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context,AsyncCallback cb,Object extraData)+16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication .IExecutionStep.Execute()+8862580
System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&完成异步)+184

我的代码是:



// AppStart_NinjectMVC3.cs

  using System.Web.Mvc; 
使用Ninject.Modules;

[assembly:WebActivator.PreApplicationStartMethod(typeof(MyApp.AppStart_NinjectMVC3),Start)]

命名空间MyApp
{
using Microsoft.Web .Infrastructure.DynamicModuleHelper;



使用Ninject;

public static class AppStart_NinjectMVC3
{
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpApplicationModule));
}
}
}

// NinjectHttpApplicationModule.cs

 使用MyApp.Data; 
使用NHibernate;

命名空间MyApp
{
using System;
使用System.Web;

使用Ninject;
使用Ninject.Web.Mvc;

public sealed class NinjectHttpApplicationModule:IHttpModule,IDisposable
{
#region Ninject Mvc3扩展引导程序(不要触摸这个代码)
private static readonly Bootstrapper bootstrapper = new Bootstrapper ();
私有静态bool初始化;
private static bool kernelDisposed;

///< summary>
///初始化模块并准备好处理请求。
///不要改变这个方法!
///< / summary>
///< param name =context> An< see cref =T:System.Web.HttpApplication/>可以访问ASP.NET应用程序中的所有应用程序对象的方法,属性和事件< / param>
public void Init(HttpApplication context)
{
lock(bootstrapper)
{
if(initialized)
{
return;
}

initialized = true;
bootstrapper.Initialize(CreateKernel);
}
}

///< summary>
///配置< see cref =T:System.Web.HttpApplication/>实例。
///不要改变这个方法!
///< / summary>
public void Dispose()
{
lock(bootstrapper)
{
if(kernelDisposed)
{
return;
}

kernelDisposed = true;
bootstrapper.ShutDown();
}
}
#endregion

///< summary>
///创建将管理您的应用程序的内核。
///< / summary>
///< returns>创建的内核。< / returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
RegisterServices(kernel);
返回内核;
}

///< summary>
///加载您的模块或在这里注册您的服务!
///< / summary>
///< param name =kernel>内核< / param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind< ISession>()。ToMethod(x => kernel.Get< SessionFactoryBuilder>()。CreateFactory() 。())InRequestScope();
kernel.Bind< ITransaction>()。ToMethod(x => kernel.Get< ISession>()。BeginTransaction())InRequestScope()
kernel.Bind(typeof(IRepositoryBase)))To(typeof(RepositoryBase;));
kernel.Bind< IUnitOfWork>()。To< UnitOfWork>();
}
}
}

大多数代码是默认情况下,您可以通过NuGet进行安装。我所做的仅仅是添加一些绑定到 RegisterServices()



任何建议?

解决方案

修正于2.2.1.0



参见获取更多信息。


I've just installed the new Ninject.MVC3 from NuGet and trying to make it work in my asp.net mvc 3 app, however I get this weird error now and then when surfing my site:

[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 d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\Components\ComponentContainer.cs:146
   Ninject.Components.ComponentContainer.Get() in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\Components\ComponentContainer.cs:102
   Ninject.KernelBase.CreateContext(IRequest request, IBinding binding) in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\KernelBase.cs:540
   Ninject.<>c__DisplayClassa.<Resolve>b__6(IBinding binding) in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\KernelBase.cs:375
   System.Linq.<>c__DisplayClass12`3.<CombineSelectors>b__11(TSource x) +20
   System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +151
   System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4178557
   Ninject.Web.Mvc.NinjectDependencyResolver.GetService(Type serviceType) in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectDependencyResolver.cs:56
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +51

[InvalidOperationException: An error occurred when trying to create a controller of type 'MyApp.Controllers.NewsController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +196
   System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
   System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8862580
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

And my code is:

// AppStart_NinjectMVC3.cs

    using System.Web.Mvc;
    using Ninject.Modules;

    [assembly: WebActivator.PreApplicationStartMethod(typeof(MyApp.AppStart_NinjectMVC3), "Start")]

    namespace MyApp
    {
        using Microsoft.Web.Infrastructure.DynamicModuleHelper;



  using Ninject;

    public static class AppStart_NinjectMVC3
    {
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpApplicationModule));
        }
    }
}

// NinjectHttpApplicationModule.cs

using MyApp.Data;
using NHibernate;

namespace MyApp
{
    using System;
    using System.Web;

    using Ninject;
    using Ninject.Web.Mvc;

    public sealed class NinjectHttpApplicationModule : IHttpModule, IDisposable
    {
        #region Ninject Mvc3 extension bootstrapper (Do not touch this code)
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();
        private static bool initialized;
        private static bool kernelDisposed;

        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// Do not change this method!
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
        public void Init(HttpApplication context)
        {
            lock (bootstrapper)
            {
                if (initialized)
                {
                    return;
                }

                initialized = true;
                bootstrapper.Initialize(CreateKernel);
            }
        }

        /// <summary>
        /// Disposes the <see cref="T:System.Web.HttpApplication"/> instance.
        /// Do not change this method!
        /// </summary>
        public void Dispose()
        {
            lock (bootstrapper)
            {
                if (kernelDisposed)
                {
                    return;
                }

                kernelDisposed = true;
                bootstrapper.ShutDown();
            }
        }
        #endregion

        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            RegisterServices(kernel);
            return kernel;
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<ISession>().ToMethod(x => kernel.Get<SessionFactoryBuilder>().CreateFactory().OpenSession()).InRequestScope();
            kernel.Bind<ITransaction>().ToMethod(x => kernel.Get<ISession>().BeginTransaction()).InRequestScope();
            kernel.Bind(typeof(IRepositoryBase<>)).To(typeof(RepositoryBase<>));
            kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
        }
    }
}

Most of the code is the default one you get when installing by NuGet.. the only thing I've done is to add some bindings to the RegisterServices()

Any suggestions?

解决方案

Fixed in 2.2.1.0

See http://www.planetgeek.ch/2011/03/01/ninject-2-2-1-0-and-ninject-mvc3-2-2-1-0-released/ for more information.

这篇关于Ninject +“加载Ninject组件ICache时出错”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:19