【问题标题】:Unit Of Work - related repository工作单元相关的存储库
【发布时间】:2019-08-14 21:24:41
【问题描述】:

我有 10 节 POCO 课。 我正在使用带有 IRespoitory 接口和 UnitOf 工作类的工作单元的简单存储库模式。

将我所有的 IRepository 放在一个 UnitOfWork 实例中是否正确(正常)?

即: 10 个 POCO 类 - 10 个 IRepository 实例 - 只有一个 UnitOfWork 类包含所有 10 个存储库

UnitOfWork
{
IRepository<Customer> CustomerRepository {get; set;}
IRepository<Customer> CustomerRepository {get; set;}
IRepository<Customer> CustomerRepository {get; set;}
// the same for all others 7 POCo class
// ..other stff
}

【问题讨论】:

    标签: entity-framework c#-4.0 repository-pattern unit-of-work


    【解决方案1】:

    有点像EF DataContext

    EntityFramework 的DataContext 是一个工作单元,有点像存储库(或存储库的集合 >)。

    我更喜欢将这些东西分开并使用依赖注入框架(如结构映射)。

    您可以向 structuremap 询问IRepository&lt;Customer&gt;,它会为您提供实例。

    UoW与您的存储库分开。

    你可以有一个 UoW 类(使用类似SubmitChanges 的方法),然后是你的Repositories(每一个都有类似:Add, Delete, ... 的方法)

    【讨论】:

      【解决方案2】:

      是的,您的方法是正确的(正常),一个工作单元类/实例包含所有(POCO 类的)存储库。

      UoW 为我带来了 2 个重要的东西/优势;

      1. 显而易见的是 ACID(原子、一致性、隔离、持久性)事务,因为只有一个 dbcontext 跟踪和更新所有 db 更改。

      2. Unit of Work reduce a lot of dependency Injection.

      这是一个使用 UoW 和存储库的完整示例;

      public interface IUnitOfWork
      {
          IRepository<Customer> Customers { get; }
          IRepository<Order> Orders { get; }
          // the same for all others 8 POCO class
      
          Task<int> SaveAsync();
      }
      

      ================================================ ===============

      public class UnitOfWork : IUnitOfWork
      {
          public IRepository<Customer> Customers { get; private set; }
          public IRepository<Order> Orders { get; private set; }
          // the same for all others 8 POCO class
      
          private readonly MyDBContext _Context;
      
          public UnitOfWork(MyDBContext context)
          {
              _dbContext       = context;
              Customers        = new Repository<Customer>(_dbContext);
              Orders           = new Repository<Order>(_dbContext);
              // the same for all others 8 POCO class
          }
      
          public async Task<int> SaveAsync()
          {
              return await _dbContext.SaveChangesAsync();
          }
      }
      

      您可以在上面的实现中看到一个 dbContext 已用于生成所有存储库。这将带来 ACID 功能。

      在您的服务/控制器(或任何您想使用存储库的地方)中,您只需要注入 1 个 UoW 并可以访问您的所有存储库:

          _uow.Customers.Add(new Customer());
          _uow.Ordres.Update(order);
          _uow.SaveAsync();
      

      【讨论】:

        猜你喜欢
        • 2013-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-10
        • 2016-06-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多