加载模块时出错' Ninject.Web.Mvc.MvcModule'类型MvcModule

时间:2014-10-11 23:16:28

标签: c# asp.net asp.net-mvc ninject ninject.web.mvc

我正在构建一个ASP.NET MVC5 Web应用程序,使用Ninject.MVC5进行DI。我正在尝试将NinjectWebCommon类移动到一个单独的类库项目中。我可以使用以下代码成功完成此操作:

private static IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    try
    {
        // Uncomment to move this file to a separate DLL
        kernel.Load("MyWebApp.dll");
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);
        return kernel;
    }
    catch
    {
        kernel.Dispose();
        throw;
    }
}

在上面的代码中,MyWebApp.dll是主Web应用程序程序集的文件名。这有效,但要求我硬编码对Web应用程序DLL的引用。我在官方文档中读到,以下内容可用于在以这种方式分离的解决方案中自动加载所有 DLL:

kernel.Load(AppDomain.CurrentDomain.GetAssemblies());

但是,如果我使用此代码而不是硬编码引用,我会收到以下异常(在上面的throw行捕获并重新抛出):

An exception of type 'System.NotSupportedException' occurred in
MyWebApp.Infrastructure.dll and wasn't handled before a managed/native boundary

Additional information: Error loading module 'Ninject.Web.Mvc.MvcModule' of
type MvcModule

任何人都可以提供一些有关此处发生的事情的信息,以及如何在避免对其他程序集进行硬编码引用的同时防止发生此异常?

1 个答案:

答案 0 :(得分:5)

创建内核时,您需要确保将LoadExtensions设置为 false

根据文件:

  

LoadExtensions:获取或设置一个指示内核是否的值   应该在启动时自动加载扩展名。

以下一行:

var kernel = new StandardKernel();

......应该成为这个:

var kernel = new StandardKernel(new NinjectSettings() { LoadExtensions = false });
相关问题