如果模块被加载两次,有没有办法让 Ninject 立即抛出异常

Is there a way to make Ninject throw exception immediately if module is loaded twice

后面的代码很简单global.asax。 CoreModule 是一套应用程序的主要模块 - 而 WebAPIModule 是一个继承自包装器 class 的模块,该包装器仅包装标准 Ninject 模块,但为依赖模块添加了一个字段。如果该字段中列出了任何内容,则会加载它们。因此,如果您碰巧将 CoreModule 列为依赖项,但具有以下代码,则 CoreModule 将被加载两次。这会产生来来去去的瞬态错误,并且很难可靠地找到。如果两次加载相同的类型,有没有办法让 Ninject 抛出异常或更快地失败?我还没见过,但如果有一种快速失败的方法就好了。

public class WebApiApplication : NinjectHttpApplication
    {
        protected override void OnApplicationStarted()
        {
            base.OnApplicationStarted();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

        }

        protected override IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            RegisterServices(kernel);
            return kernel;
        }

        private void RegisterServices(IKernel kernel)
        {
            kernel.Load<CoreModule>();
            kernel.Load<WebAPIModule>();
        }

    }

你在动态加载程序集吗?

如果您尝试加载已经加载的模块,

Ninject 将抛出错误。

您可以创建一个扩展方法,将内核中已存在的模块与您尝试加载的模块进行比较,并仅加载尚不存在的模块。

将这些程序集扩展方法复制到您自己的扩展方法中 class,以及以下内容:Ninject Assembly Extensions

ExtensionsForKernel.cs

    /// <summary>
    /// Loads modules from specified assemblies that don't already exist in the kernel.
    /// </summary>
    public static void LoadIfNotLoaded(this IKernel kernel, IEnumerable<Assembly> assemblies)
    {
        var existingModules = kernel.GetModules();
        var newModules = assemblies.SelectMany(a => a.GetNinjectModules())
            .Where(m => !existingModules.Any(em => em.GetType() == m.GetType()));
        kernel.Load(newModules);
    }

NinjectWebCommon.cs

    private static void RegisterServices(IKernel kernel)
    {
        kernel.LoadIfNotLoaded(AppDomain.CurrentDomain.GetAssemblies());
    }