.Net Dependency injection in unit of work pattern using repositories

一曲冷凌霜 提交于 2019-12-24 04:23:09

问题


I'm a relative noob to the concept of Dependency Injection, and have been trying to glean the best practices before starting a new project.

Looking at the top answer to Dependency injection in unit of work pattern using repositories I understand the approach, but the example code seems to be missing something, and I'm stumped...

The definition of the interface IRepository is shown as:

public interface IRepository 
{
    void Submit();
}

But when the interface is used as part of the definition of the GenericRepository class, the Submit method is not implemented:

public abstract class GenericRepository<T> : IRepository<T> where T : class
{
    public GenericRepository(IUnitOfWork unitOfWork)
    {
        unitOfWork.Register(this);
    }
}

Then, a repository class for a specific entity is defined, inheriting from GenericRepository:

public class DepartmentRepository : GenericRepository<Department> 
{
    public DepartmentRepository(IUnitOfWork unitOfWork): base(unitOfWork) { }
}

My question is, given that each different entity's repository may need a reference to a different DataContext, how should the generic Submit() method be implemented using DI?


回答1:


The question you link to was a solution to ensure that the Unit Of Work was always aware of Repositories; the repository implementation itself was pretty useless! A Repository should, as a minimum, expose methods for all crud operations:

public interface IRepository<TEntity, in TKey> where TEntity : class
{
    TEntity Read(TKey id);
    TEntity Add(TEntity entity);
    TEntity Update(TEntity entity);
    void Delete(TKey id);
}

See this article for example.



来源:https://stackoverflow.com/questions/29969681/net-dependency-injection-in-unit-of-work-pattern-using-repositories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!