2

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?

Liam
  • 27,717
  • 28
  • 128
  • 190
user2209634
  • 529
  • 7
  • 27
  • `IRepository` != `IRepository` There must be another interface with the generic declared which doesn't define the Submit method. – Liam Apr 30 '15 at 13:59
  • But then it also says: `public interface IRepository :IRepository where T : class { }` so that's somewhat confusing. – Liam Apr 30 '15 at 14:02
  • 1
    I believe in this instance that the Submit method is left undefined as it would be implementation specific, and the answer is specifically relating to how to relate the UoW and the repository, rather than to a particular implementation: note the UoW code does call Submit - `_repositories.ToList().ForEach(x => x.Value.Submit());` – stuartd Apr 30 '15 at 14:05

1 Answers1

4

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.

qujck
  • 14,388
  • 4
  • 45
  • 74