为洋葱架构中的 Ninject 个模块设置范围

Set Scope for Ninject Modules in Onion Architecture

我在 Visual Studio 中有多个项目,每个程序集都有一个 Ninject-模块定义。此解决方案的结构为 "Onion Architecture"。模块仅在引用程序集的项目中加载。

我有这些图层

目前 Web-UI - 层不需要引用存储库,因为 BusinessLayer 的 Ninject-Moduleloader 从 Repository-Moduleloader

我的 Repository-Layer 没有任何对 ASP.Net 程序集的引用。所以我无法将 Ninject 模块的范围设置为 "InRequestScope"。我现在正在尝试在我的 WebUI-Layer 中设置 ModuleLoader 的配置,但是存储库的模块仍然不是 "InRequestScope"

private static void RegisterServices(IKernel kernel) {           
    kernel.Bind(i => i.From("*.dll")
    .SelectAllClasses()
    .BindDefaultInterface()
    .Configure(x => x.InRequestScope()));

    kernel.Load(new BusinessLayer.BusinessLayerModuleLoader());
    kernel.Load(new WebUIInjector());
}
  1. 为什么此配置不适用于由 BusinessLayerModuleLoader 本身加载的模块?
  2. 第一个语句是只绑定配置,还是它已经从“*.dll”找到的所有程序集中加载Ninject模块?在那种情况下,我不需要第二条语句 "kernel.Load(new BusinessLayer..." 对吗?

第一个语句 (kernel.Bind(i => i.From(....));) 在所有部署的 *.dll 中搜索具有与“默认接口”约定匹配的接口的类型,即:类型名称以接口名称结尾(没有前导 I) ,例如:“Foo --> IFoo”、“Bar --> IBar”、“SomeFoo : IFoo”。 它不加载任何模块

Kernel.Load 运行s NinjectModule 的 Load 方法可以添加额外的绑定。 首选的替代方法是使用 kernel.Load<BusinessLayer.BusinessLayerModuleLoader>() 并将其命名为 BusinessLayerModule 而不是 BusinessLayerModuleLoader.

加载所有已部署 dll 的所有模块运行:kernel.Load("*.dll");。 有关模块和模块加载的更多信息,请参阅:https://github.com/ninject/Ninject/wiki/Modules-and-the-Kernel

注意:如果一个模块要执行 Bind<IFoo>().To<Foo>(),那么 IFoo 会有 2 个绑定,因为约定已经绑定了它。这将导致带有消息 ...more than one matching binding available....

NinjectActivationException

提示:关于如何参数化 NinjectModule 中应用的范围的问题已经在 SO 上提出过。