In this example we will first implement a sample application using pure MVC architecture and then we will see how to improve our code standards by implementing the repository design pattern.
The MVC framework is one of the common design patterns in modern web applications. It provides complete separation of concerns. But even MVC is not a silver bullet of all problems. On top of MVC we can implement various design patterns to solve the specific problem.
In this example we will first implement a sample application using pure MVC architecture and then we will see how to improve our code standards by implementing the repository design pattern. So, let's start with one example.I will suggest you to create one MVC application. Let's create the table at first then we will set up the Entity Framework in the application. Here is the table stricture.
Ok, we understad the problem; how to solve it? The solution is the Repository Design Pattern, we will totally isolate the DB operation part into a different class and we will consume the service (yes, let's think of the class as a service class) into our actual controller class.For that, at first we will create an interface and create a repository for CRUD operations, then we will implement the interface within the concrete class.So, the following is the Interface implementation.
There are five functions within this Interface that we will implement in a class shortly. Here, we have implemented an ICompany interface within a “CompanyRepositary” class. Have a look at the following example.Repository class for CRUD operation
We will now consume the repository service within our actual controller class. Here is the controller implementation. Now, have a look that, we have totally isolated the DB operation from our controller class. So that, now the Company controller is de-coupled in nature and we have injected a dependency through the controller.Implementation of Company repository in controller
The great advantage in this de-coupled architecture is unit testing. If we create one mock repository class and inject it in a controller then we can avoid execution of the DB part at the time of unit testing. I am interested in implementing and showing it in my next article. So, please follow my next article here.
ASP.NET MVC 5: A Beginner’s Guide