Simple And Best Way of Implementing the Repository Pattern


What is Repository Pattern?

I have seen so many ways to write repository pattern. I have read Rob Conery's blog also.

But, according to my experience, the repository pattern is the one constructing criteria by client code and passing it to repository.

A repository is nothing but a mediator between data access layer and business layer.

I will try to explain in a very simplest method to understand repository pattern.

Step 1:

Create VS 2010 project and name it RepPattern.

I have created here a Silverlight application. Because I really like to work with Silverlight.

RepoPtrn1.jpg


In this application, I have added two folders.

  1. Contract:

    To hold all interface entity.

    That is IPattern interface.
     
  2. Service:

    To hold all interface implemented class.

    That is PatternService class.

Step 2:

In IPattern interface, I have declared signature to get some value. I. e Get default name.

At the same time I have implemented IPattern interface on PatternService class as given below.


RepoPtrn2.jpg

These modules belongs to the repository.

Step 3:

Now, it's the time to actually implement this repository.

Here I have added one more class called PatternHelper.cs. Also, I have written one static method to return all repository methods.


RepoPtrn3.jpg
Step 4:

Next one is calling these repository methods from client.

RepoPtrn4.jpg

Step 5:

Run the application.

RepoPtrn5.jpg

As I said before, repository is nothing but a mediator between business logic and data access layer.

Here, PatternHelper works as repository layer.

These separation of business logic and data helps in three ways.
  • It centralizes the data logic or Web service access logic.
  • It provides a substitution point for the unit tests.
  • It provides a flexible architecture that can be adapted as the overall design of the application evolves.

Usage of Repository pattern:
  1. We can use this pattern to access a data source from many locations yet centrally manage the data source.
  2. We can test it individually (Unit test).
  3. Code maintainability. 


Thanks
Enjoy the coding!!!!!


Similar Articles