简体   繁体   中英

.Net Dependency injection in unit of work pattern using repositories

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM