Search This Blog

Sunday, May 28, 2017

Design Pattern : What is repository pattern?

Repository Pattern separates the data access logic and maps it to the entities in the business logic. It works with the domain entities and performs data access logic. In the Repository pattern, the domain entities, the data access logic and the business logic talk to each other using interfaces. It hides the details of data access from the business logic. In other words, business logic can access the data object without having knowledge of the underlying data access architecture. For example, in the Repository pattern, business logic is not aware whether the application is using LINQ to SQL or ADO.NET Entity Model ORM. In the future, underlying data sources or architecture can be changed without affecting the business logic.

There are various advantages of the Repository Pattern including:

  • Business logic can be tested without need for an external source
  • Database access logic can be tested separately
  • Database access logic will hide the data access implementation details to the business logic(will create an abstraction between data access logic and business logic)
  • Business logic will not get impacted from the any changes happened in data access logic
  • No duplication of code
  • Caching strategy for the datasource can be centralized
  • Domain driven development is easier
  • Centralizing the data access logic, so code maintainability is easier

Repository acts as a mediator between business logic and data source(database).

How to Implement Repository pattern in C#

The way to implement repository pattern in any application is as:
  1. Define an interface for the repository.The interface declares the database operations.
  2. Create a class which implements the above interface and provides the implementation for the interface methods
  3. Access the repository from the business layer through the interface.

Step 1 : Define interface

Its highly recommended that an architecture must create a generic repository interface only.

Step 2 : Create Repository

Implement the database operation defined in step 1(IRepository)

In above code EntityBase is a base class for all entities which has an ID property of type Int.

Step 2 : Access repository from business logic

To access repository from business logic, create an instance of repository in business logic and use it as per requirement.

No comments:

Post a Comment