Published in


Repository Pattern with Dependency Injection — MVC EF Code First

We are going to discuss the one of the most widely used a pattern called Repository Pattern. By using the repository pattern an application can have a clear separation between Business Layer and the Data Layer.

As per the above diagram, Repository layer decouples the Domain logic from Data access logic hence Business Layer has no knowledge of Data Layer and vice versa. The operations/ communications between Business Layer, Data Layer with Repository Layer are implemented using Interface classes. (You will see later in this tutorial). Each layer has its own responsibilities and this is a clean example of Separation of Concerns(SoC).


  • Centralized the data access logic therefore easy to maintain.
  • Redundant Code.
  • Provide great facility to write unit tests for Data Layer.
  • Improves the readability.


  • Though this reduces the number of lines of code you need to write, it increases the number of classes needs to maintain and this may increase the complexity of the project.
  • The code still can be duplicated unless using Generic Repository classes.
  • It is difficult to unit test the repositories still need to have an Integration test.
  • Using this pattern with ORMs such as Entity Framework, NHibernate will distance from its features. Such an obvious example is Include method which one can retrieve the data with Eager Loading.

Now let’s see how to implement the Repository pattern with Dependency Injection using EF code first approach. In this example, I’m using Visual Studio Community Edition 2017.

First, create a new C# web Application and name it as ‘StudentsManagement’.

Then select MVC and keep other settings as default and click ok. Visual Studio generates basic MVC structure as follows.

Since we are using Entity Framework as ORM in our example we need to install EF NuGet Package Manager using the console or Manage Package for Solution option. In this tutorial, we will be using Manage Package for Solution to install EF.

Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution -> Browse tab
and type entity and enter. Then select the Entity Framework and the project, click install.
The latest stable version of EF now is 6.2.0 as of now.

Add Domain Entity

Then we need to create the domain classes and Let’s create a ‘Student’ entity inside the ‘Models’ folder in the solution.

DataAnnotations is used define the primary key and auto increment Id using ‘Key’ and
‘DatabaseGenerated(DatabaseGeneratedOption.Identity)’ respectively. In order to use aforementioned Data annotations include,
System.ComponentModel.DataAnnotationsand System.ComponentModel.DataAnnotations.Schema namespaces.

Build the solution to update the references.

Add Student Controller

Right-click on the Controllers folder, Add -> Controller then -> MVC 5 Controller with views, using Entity Framework -> Add

Select Student from the Model class drop-down, then click + and change the context name to ‘StudentDbContext‘(This will be your context class). Leave the rest of the fields as it is. Finally, it would look like as follows.

MVC 5 with Entity Framework scaffolding has created method stubs which contains all the CRUD operations related to Student Entity. Press Ctrl + F5 and navigate to Students Controller.

To your surprise project compiles successfully and displays the above screen. This is the beauty of EF scaffolding. EF has created a database called ‘StudentDbContext‘ locally, added the entity property(Dbset<Student> Students { get; set; })and created the connection string to the local database in Web.config too. We will discuss more on that in another lesson.
Let’s add some sample data to the database by using ‘Seed’method.

Add a new class called ‘SchoolDbInitializer’ and inherit one of the databases Initialization strategy as ‘DropCreateDatabaseIfModelChanges‘. The database will be dropped and re-created whenever the model changes, then override the seed method to add sample data when the database is created.

If you hit Ctrl + F5 and navigate to Students controller your view will be as follows.

Index Page

Now will implement the repository pattern for the Students Controller.

  1. Create a folder called Repositories
  2. Add an Interface as ‘IStudentRepository’
  3. Replace with the following code.

Then add a new class as ‘Student Repository’ in the Repositories folder and replace with the following code.

We will implement each of these methods after adding the Dependency Injection.

Dependency Injection

Dependency Injection (DI) is a software design pattern, a particular case of Inversion of Control (IoC) pattern. IoC says high-level module should not depend on a low-level module, and both should depend on the abstraction. Basically, DI is a mechanism of injecting low-level instance to a high-level module. For an example.

There are many IoC containers which provide the facility to Inject a dependency upon request. Following are few of the popular IoC containers.

  • UnityContainer
  • Castle Windsor
  • NInject
  • Structure Map

We are going to use Unity.Mvc5 which is an implementation of UnityContainer. We will use NuGet package manager console to install Unity.Mvc5.

Tools->NuGet Package Manager -> Package Manager Console
Then in the console type Install-Package Unity.MVC5 and hit enter. This will all the necessary assemblies and UnityConfig.cs file in the App_Start folder.

First, we need to register the UnityContainer. Add following line in the Application_Start() in the Global.asax file

Then we need to register our components with UnityContainer in the UnityConfig.cs file.

Then add the following line in StudentRepository.cs class and add the namespace as using Unity.Attributes;
StudentDbContext DbContext { get; set; }

UnityConfig will resolve the StudentDbContext using the Dependency Resolver so that an instance of StudentDbContext is accessible in the Student Repository class. Therefore one does not need to have an integration testing rather use unit testing to verify the functionalities of the Repository class.

So that we can complete the implementation of StudentRepository class as follows.

Since above code is pretty straightforward I will not explain it. It is about updating and retrieving information from the DB server.

Then add the IStudentRepository implementation in StudentsController.

The IStudentRepository interface will be resolved and injected into the constructor of StudentsController with the help UnityContainer resolver. So that now we can use the instance of IStudentRepository (i.e. studentRepository) to invoke CRUD operations in StudentRepository class.

Please note that here I have shown the only a couple of controller action methods only. You can change the rest of the actions as above. Press Ctrl + F5 and redirect to the Students controller and see the changes.

Congratulations!! You have just created an MVC application using Dependency Injection and Repository pattern with EF code first.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lakshitha Fernando

Lakshitha Fernando


Technical Lead at Camms. A graduate of University of Colombo School of Computing Sri Lanka. Microsoft certified programmer | Traveller | Hiker and Bookworm