簡體   English   中英

工作單元和存儲庫模式

[英]Unit of Work and Repository Pattern

我想在我的應用程序中實現簡單的 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 用於寫入和 Repository 用於讀取,是否應該有用於寫入的 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 關系的解釋,或者類似於這個實現的好教程都會有所幫助。

問候。

我認為就是您所需要的。 一篇文章中的所有標簽)

對於插入/更新,我建議您避免使用 Repository 模式。

您應該考慮將“命令/查詢對象”作為替代方案,您可以在該領域找到一堆有趣的文章,但這里有一篇很好的文章:

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

您將堅持每個命令使用一個命令對象來啟用簡單的事務,從而避免工作單元模式的復雜性。

但是,如果您認為每個查詢一個 Query 對象是矯枉過正,這通常是正確的。 相反,您可以選擇從“FooQueries”對象開始,它本質上是一個存儲庫,但僅用於查詢。 'Foo' 可能是 DDD 意義上的“域聚合”。

稍后,如果您想通過屬性添加橫切關注點,您可能會發現拆分單個查詢對象是值得的,您甚至可以將查詢對象輸入到管道中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM