【问题标题】:MVC Ninject with Multiple Projects具有多个项目的 MVC Ninject
【发布时间】:2015-03-07 02:21:09
【问题描述】:

Ninject 的新手。我有一个这样的项目....

表示层 > 服务层 > 数据访问层

我在 Presentation Layer 上安装了 Ninject,所以我的控制器可以在 Service Layer 上正常工作(因为我的 Presentation Layer 有 对服务层的引用)。

这是一个示例(我的 Presentation 层的 NinjectWebCommon.cs 中的代码):

'Works within my Presentation Layer
kernel.Bind<Service.IOrders>().To<Serice.Orders>();

'Does NOT Work within my Presentation Layer since it does not know about my dataAccess layer
kernel.Bind<DataAccess.IOrdersRepository>().To<DataAccess.OrdersRepository>();

那么我该如何设置我的 Ninject,以便我可以从一个地方注入而无需引用我的数据访问层。

【问题讨论】:

    标签: asp.net-mvc dependency-injection ninject


    【解决方案1】:

    使用依赖注入,应该有一个知道所有绑定的组合根。 另请参阅 Mark Seeman 在Composition Root 上的博客条目。

    这意味着它需要引用您的 DAL。 如果您确实需要将表示层与 DAL 分开,那么您需要将组合根提取到不包含表示层的单独程序集(应用程序)中。应用程序程序集将定义所有绑定并组成对象图。为此,它需要引用所有其他程序集(表示层、DAL 等等)。

    但是,ninject 和 AutoFac 提供了一个稍微不同的设计选择:模块(有关 ninject 的描述,请参阅 here)。在 Modules @ DAL 程序集中定义 DAL 绑定,在模块 @ 表示程序集中定义表示绑定,然后反射以加载所有已部署程序集的所有模块。例如:

     -- presentation.dll
        - PresentationModule : NinjectModule
         --> defines presentation bindings
     -- dal.dll
        - DataAccessModule : NinjectModule
         --> defines data access bindings
     -- app.dll (asp.net mvc application)
       - creates kernel
       - then searches for all deployed *.dll's,
         in those it searches for all implementations of `NinjectModule`
         and then loads these. This is done by:
         kernel.Load(AppDomain.CurrentDomain.GetAssemblies())
       - does not reference dal.dll or presentation.dll!
    

    请注意,我不确定AppDomain.CurrentDomain.GetAssemblies() 是否适用于 asp.net 应用程序。也许您需要其他方法来查找所有已部署的程序集。

    另请注意,除非您需要有层(另请参阅here)或更改层而不重建整个应用程序,否则没有必要为单独的层使用单独的程序集。

    还有一些类似的问题有答案:

    你可能还想看看this blog post

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      相关资源
      最近更新 更多