c# - 加载 MvcModule 类型的模块 'Ninject.Web.Mvc.MvcModule' 时出错

标签 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

谁能提供一些信息,说明这里发生了什么,以及如何在避免对其他程序集进行硬编码引用的同时防止此异常发生?

最佳答案

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

根据文档:

LoadExtensions: Gets or sets a value indicating whether the kernel should automatically load extensions at startup.

下面一行:

var kernel = new StandardKernel();

...应该变成这样:

var kernel = new StandardKernel(new NinjectSettings() { LoadExtensions = false });

关于c# - 加载 MvcModule 类型的模块 'Ninject.Web.Mvc.MvcModule' 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26320244/

相关文章:

c# - 我如何确定与网络服务器的连接是否使用完美前向保密?

c# - 您可以让扩展器覆盖 WPF 中的其他可视化树元素吗?

c# - 在 Entity Framework 中使用 'using' 语句的正确方法

c# - Html.CheckBox 呈现两个复选框

c# - 在 asp.net core 3.0 中为角色 SecurityStamp 创建 ClaimsIdentityOptions

c# - 如何在 ASP.NET MVC 中选择数据访问方法?

c# - 如何在 linq 中对子列表求和?

c# - 如何从 ASP.NET MVC 中的不同 Controller 和操作呈现的 Html.Action 中检索 Controller 和操作名称

c# - 如何确定另一个应用程序的窗口是否可见?

c# - Microsoft Office Interop Excel ExportAsFixedFormat - 非常慢,图像未加载