Repository Design Pattern : Implementing Generics, MOQ, MSTEST In ASP.NET MVC

Repository Design Pattern is a way to encapsulate repetitive data access code.

Repository Pattern is effective data access design pattern when we want to:
  • Increase testability of the application. Make test repeatable without touching the data source;
  • Implement Separation of Concerns between the business logic and data source or business logic and test units;
  • Make the application work with different data source such SQL Server, mySQL, Oracle, web api endpoints, xml file and other RDBMS out in the market.
  • Make our code reusable. Effective on CRUD.
Repository is simply Persistent Ignorant, it does not care what data store it will be using. It works on in-memory data instead of the actual data coming from files.

Today, we are going to see how to implement this in ASP.NET MVC.



THE ARCHITECTURE

We are going to use Domain Centric Design architecture in this application so we need the following layers:
  • Core = Contains the business logic that includes the Generic Repository interface and the  POCO models.
  • Data = Layer that handles SQL Data Access
  • MVC = The UI
  • Test = Unit Tests
Architecture[8]

THE CORE LAYER

The POCO Models:

Country.cs


Client.cs


The Generic Repository Interface

In order to implement Dependency Injection and mocks, we need to use interface.

The advantage of using generics in repository is that is it reusable. We can reuse the repository by passing the class as parameter.

THE DATA LAYER

In the Data Layer we will use EF First Code approach. This is where we will implement the generic repository. We can use this in both Country and Client class.

EFClientDb.cs


THE MVC

For the purpose of demonstration, we will be having some business logic in the controller level. But in production, it is recommended to push this business logic to the core layer.

This is where the Generic Repository is at its best. We can just change the parameter with the class we are working without adding another layer of abstraction in order to be specific on the entity we are working on.

CountryController.cs

We can also apply this approach to ClientController. I will leave this to the readers. Try it yourself.

With regards with the views for this controller. It work like a normal mvc views.


THE TEST

This is another endpoint that we could expose the Repository. We can use fake data to test the controllers but we will be using Moq framework to test the CountryController (it much easier).

MoqCountryController.cs


That's it! Thank you for time. I hope this article is helpful. Share it with your friends.