Wednesday, November 30, 2016

Repository Pattern - Example

This is the continuation of the previous post. Here I will be discussing the approach I have taken to implement repository pattern in the same 2 page bank application, we have discussing in couple of previous posts.


Except the Presentation Layer all the other projects are .net class library projects. Lets discuss each, one by one:

  • Entities Layer source code:
    • Define a base class Entity.
    • Make all the entity classes inherit from the calss Entity.
      • AccounHolder
      • Account
      • Transaction

    • Create context for all the entities
  • Repository Layer source code:
    • Create a generic interface called IGenericRepository

    • Create a generic repository called GenericRepository which implements IGenericRepository interface.

    • Make following repositories classes (which inherit from BaseRepository class) for each of the database entities.
      • AccoutHolderRepository
      • AccountRepository
      • TransactionRepository

  • Business Layer source code:
    • Create generic interface IBaseService Centralises Data Access logic or Web Service Access logic.

    • Create a generic base class which implements IBaseService interface created above and takes two generic parameter:
      • "T" for the entity type
      • "R" for the repository type
    • Create service class for each for database entities, and make them inherit the BaseService class created above.
      • AccountHoldersService
      • AccountsService
      • TransactionsService
  • Presentation Layer source code:
    • Below is the example of how the business layer is being called from Presentation layer 
In current application the database context is being moved to Repository Layer from Business Layer, now Business Layer can be unit tested by mocking repository. So now, we can confidently say, introducing Repository Layer between DAL and BL, removes the tight coupling between them. 



There is still an issue with this approach, if I want to introduce Unit of Work with Repository, it will be really hard to implement that. In my next post I will be refactoring this to use only the Generic Repository and will be covering, how Unit Of Work pattern can be used with Repository pattern to get rid of concurrency issues, that comes when multiple repositories are being used in a single transaction. 

PS: Repository pattern can be used with or without the Unit of Work pattern.

1 comment:

  1. Great Work. Appreciable

    Thanks to write about design pattern.

    ReplyDelete