c# - EntityFramework 和 IoC 接口(interface)在洋葱架构中属于什么位置?

标签 c# design-patterns dependency-injection domain-driven-design inversion-of-control

我最近发现了 Jeffrey Palermo 的洋葱架构模式,并出于好奇决定将其用于当前的项目。由于一个错误导致我的 IoC 框架 (Unity) 完全无法用于我的项目,因此我不得不将其替换为另一个框架 (Ninject) 后,我注意到我做出了正确的决定,因为我只需要更改我的 IoC 框架 (Unity) 中的几个部分。应用程序,它仍然运行得很好。

但是,我还没有弄清楚与 Entity Framework 和 IoC 相关的某些接口(interface)在此模式中属于何处。假设我有一个用于数据库上下文的接口(interface):

public interface IDatabaseContext : IDisposable {

   IDbSet<T> Set<T>() where T: class;

}

这现在是域接口(interface)吗?或者基础设施接口(interface)?需要 IDbSet<>'1 类型的接口(interface)成员将接口(interface)与 Entity Framework 紧密耦合,但我需要一种方法将数据库上下文的 transient 实例注入(inject)存储库。 IoC 是否适合洋葱架构?您对这个结构有何看法:

MyProject.Domain
    - Entities
        - MyEntity.cs
MyProject.Domain.Interfaces
    - IDatabaseContext.cs       // that doesn't fit here, right?
    - IMyEntityRepository.cs
MyProject.Infrastructure
    - Repositories
        - MyEntityRepository.cs
        - DatabaseContext.cs
    - Migrations
        ...
MyProject.Web
    - ... // web stuff
    - NancyBootstrapper.cs
MyProject.Application
    - Services
        - ISnmpClientService.cs
        - SnmpClientService.cs
MyProject.Server
    - KernelHelper.cs 
    - IKernelResolver.cs

最佳答案

依赖注入(inject)(DI)非常适合洋葱架构; that's where you should end, if you correctly apply DI .

接口(interface)应该由使用接口(interface)的客户端定义和拥有。如Agile Principles, Patterns, and Practices解释一下,“客户端[…]拥有抽象接口(interface)”(第 11 章)。因此,任何定义像 IDatabaseContext 这样以数据为中心的接口(interface)的尝试都迟早会引起问题,因为它违反了各种 SOLID 原则,例如依赖倒置原则或接口(interface)隔离原则。

相反,您的客户端代码应该定义它们所需的接口(interface)。然后,您始终可以使用 Entity Framework 实现这些接口(interface)。

关于c# - EntityFramework 和 IoC 接口(interface)在洋葱架构中属于什么位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22126915/

相关文章:

python - 设计模式名称 : get class from class level

.net - 支持 Compact Framework 的 IoC/DI Container

php - 如何在 Laravel 之外使用 Laravel 的 IOC 容器进行方法注入(inject)

c# - 列宽的数据注释

c# - 在 C# 中使用 switch 语句时遇到问题

C# MySQL 执行 UPDATE 什么都不做

javascript - Javascript什么时候打破了MVC模式

oop - 游戏架构: Class leaking into almost all files

c# - Admob 测试 xamarin android

java - 多类匹配