Aug 21, 2014

Generic Repository and Unit of Work Pattern, Entity Framework, Unit Testing, Autofac IoC Container and ASP.NET MVC [Part 4]

This is the summary post of the series. I would recommend you to read following posts first:

1. Implementing Generic Repository and Unit of Work Pattern With Entity Framework

2. Dependency Injection in ASP.NET MVC using Autofac and CRUD operations

3. Creating Unit Tests for the Controllers, the Service Layer and the Repository Layer Using Mock Framework

Patterns and Principles:

In the series, we implemented following patterns and principals:

Repository Pattern
Unit of Work pattern
Inversion of control and Dependency injection
DRY: Don’t repeat yourself

You would like to read also:

KISS : Keep it simple, stupid
YAGNI : You aren’t gonna need it

General Steps after Core Implementation:

1. Create Model class
2. Create Repository class by inheriting GenericRepository class.
3. Create Service class by inheriting EntityService class.
4. Add new Controller and Views for CRUD and other operations
5. Create Test class for unit and other testing

unit testing

Unit Testing:

If you are new to unit testing, see following:

unit testing

1. Create Mock object of dependencies, arguments or properties.

2. Define/Implement the methods or properties of mock object which are being used in the method to be tested.

3. Call the method with Mock objects.

4. verify the result in the assert section.

Suppose you want to test a controller method then you have to mock the service layer and setup the service methods being used in the method.
Similarly, for testing service layer method, you have to mock repository layer.

Source Code:


In this series, we implemented
1. a sample on Repository and Unit of Work with IoC container.
2. To keep a clean separation of concerns.
3. To prevent direct queries on top of entity framework in service or web layer.
4. All layers are easy to test.

Enjoy Architecture !!


  1. Hello Brij Mohan
    Thank you so much for the article.
    I have a question, how can we use this with multiple contexts? Do you have any suggestions or samples?


  2. Nice tutorial! Just a question when working with a Multi Tenant application ASP.NET MVC where on every action execution the current tenant is taking based on the subdomain. I then take the connectionstring of the tenants database. But what next? Where do I push my connectionstring to the unit of work to work with the correct database?


  3. Hi Brij, This is a great post, It was very usefull, I have a question, I would like to know how can I inject a dependence in a WCF services, like you’ve used in PersonController, I checed the Autofac documentatión but It did’nt work. Thanks in advance.

  4. Awesome thought. Professional application with automatic Injection.

    Does it comply with EF 6 concepts?
    What do you normally have in BaseEntity?

Leave a Reply

Your email address will not be published. Required fields are marked *