工作单元和存储库模式

时间:2015-07-16 21:19:26

标签: c# asp.net-mvc entity-framework repository unit-of-work

我想在我的应用程序中实现简单的IGenericRepository和IUnitOfWork接口,但我不确定这是最好的方法。

据我所知,UnitOfWork应该用于写作,而Repository应该用于阅读。我遇到过一个架构而且我非常喜欢它,但我只找到了接口而不是实现,我不知道应该如何实现它们。

public interface IGenericRepository : IDisposable
{
    IUnitOfWork CreateUnitOfWork();
    T FirstOrDefault<T>(Expression<Func<T, bool>> predicate) where T : class, IBaseEntity;
    IQueryable<T> Get<T>(Expression<Func<T, bool>> predicate = null, Func<IQueryable<T>, IOrderedQueryable<T>> sorter = null, params string[] includeProperties) where T : class, IBaseEntity;
    IQueryable<T> GetAll<T>() where T : class, IBaseEntity;
    IDbContext GetDbContext();
}

public interface IUnitOfWork : IDisposable
{
    int Commit();
    bool Delete<T>(T entity) where T : class, IBaseEntity;
    int DeleteItems<T>(IList<T> entities) where T : class, IBaseEntity;
    bool Insert<T>(T entity) where T : class, IBaseEntity;
    int InsertItems<T>(IList<T> entities) where T : class, IBaseEntity;
    bool Update<T>(T entity) where T : class, IBaseEntity;
    int UpdateItems<T>(IList<T> entities) where T : class, IBaseEntity;
}

我不确定这些是怎么回事。我应该在存储库中使用IDbContextFactory在Repository和UnitOfWork之间共享DbContext,还是应该有单独的DbContexts?如果我实现UnitOfWork for write和Repository for read,那么是否应该有UnitOfWorks DbContext用于写入和Repositorys DbContext用于读取或者它们应该共享相同的DbContext?

我真的很感谢DbContext和UnitOfWork / Repository应该如何运作。

这些将以这种方式在服务中实施:

public CustomerService(IGenericRepository repository)
{
    this.repository = repository;
    this.context = this.repository.GetDbContext();
}

public void UpdateCustomer(Customer customer)
{
    var uow = this.repository.CreateUnitOfWork();
    uow.AddForSave(customer);
    uow.Commit();
}

public List<Customer> GetAll()
{
    return this.repository.GetAll<Customer>();
}

任何帮助,有关DbContext和UoW / Repository关系的解释,或类似于此实现的好教程都会有所帮助。

问候。

2 个答案:

答案 0 :(得分:2)

我认为this就是你所需要的。 一篇文章中的所有标签)

答案 1 :(得分:0)

我建议你避免使用Repository模式,当然是为了插入/更新。

你应该考虑&#34;命令/查询对象&#34;作为替代方案,你可以在这个领域找到一些有趣的文章,但这里有一个很好的文章:

https://rob.conery.io/2014/03/03/repositories-and-unitofwork-are-not-a-good-idea/

您将坚持使用每个命令的单个命令对象来启用简单事务,从而避免了工作单元模式的复杂性。

但是,如果您认为每个查询的查询对象过度,那么这通常是正确的。相反,你可以选择以“FooQueries”开头。对象,它本质上是一个存储库,但仅用于查询。 &#39;富&#39;可能是您的域名聚合&#39;在DDD意义上。

稍后,如果您想通过属性添加横切关注点,您可能会发现拆分单个查询对象是有价值的,您甚至可以将查询对象提供给管道。