【问题标题】:Set Scope for Ninject Modules in Onion Architecture在 Onion 架构中为 Ninject 模块设置范围
【发布时间】:2015-12-12 13:33:51
【问题描述】:

我在 Visual Studio 中有多个项目,每个程序集都有一个 Ninject-Moduledefinition。该解决方案的结构为“洋葱架构”。模块仅在引用程序集的项目中加载。

我有这些层

  • 存储库
  • 业务层
  • 网页界面

目前Web-UI-Layer不需要引用repository,因为BusinessLayer的Ninject-Moduleloader从Repository-Moduleloader中获取了所有引用的绑定

我的 Repository-Layer 没有对 ASP.Net 程序集的任何引用。所以我不能将我的 NinjectModules 的范围设置为“InRequestScope”。我现在正在尝试在我的 WebUI 层中设置 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”找到的所有程序集中加载了 NinjectModules?在那种情况下,我不需要第二条语句“kernel.Load(new BusinessLayer...”,对吧?

【问题讨论】:

    标签: c# asp.net ninject onion-architecture


    【解决方案1】:

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

    Kernel.Load 运行 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 将有两个绑定,因为约定已经绑定了它。这将导致NinjectActivationException 带有消息...more than one matching binding available...

    提示:关于如何参数化NinjectModules 中应用的作用域的问题之前已经在 SO 上提出过。

    【讨论】:

    • 谢谢!不知道具体原因,但“*.dll”选择器对我不起作用。我不得不将其更改为我的 RepositoryDll 的名称。我也错过了这里的“IncludingNonePublicTypes”条款。现在它工作得很好!谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    相关资源
    最近更新 更多