Repository pattern - Why exactly do we need Interfaces?

前端 未结 2 1004
广开言路
广开言路 2021-01-30 02:58

I have read from internet I got this points which says Interfaces is used for this

  • Use TDD methods
  • Replace persistance engine

But I\'m not

2条回答
  •  醉话见心
    2021-01-30 03:54

    You would expose your repository as an interface:

    public interface IEmployeeRepository
    {
        List GetAll();
    }
    

    This would allow you to have many different implementations of the interface, such as the default one:

    public class EmployeeRepository : IEmployeeRepository
    {
        public List GetAll()
        {
            // Return from db.
        }
    }
    

    Or a test one:

    public class TestEmployeeRepository : IEmployeeRepository
    {
        public List GetAll()
        {
            // Stub some dummy data.
        }
    }
    

    Your code consuming the repository is then only interested in using the interface:

    IEmployeeRepository myRepo = MyRepositoryFactory.Get();
    

    The secret sauce is the factory, or another mechanism by which to resolve the interface into a usable type (a Dependency Injection framework such as Ninject, or Castle Windsor will fulfil this role).

    The point is, the consuming code doesn't care about the implementation, only the contract (the interface). This allows you to swap out implementations for testing purposes very easily and promotes loose coupling.

    Just to clarify, there is no link between the use of interfaces and the repository pattern specifically, it is just another pattern that can make use of them.

提交回复
热议问题