Click here to Skip to main content
15,867,939 members
Articles / Web Development / HTML

Repository Pattern using Dependency Injection (Autofac) in MVC application

Rate me:
Please Sign up or sign in to vote.
4.79/5 (8 votes)
19 Nov 2014CPOL4 min read 53.2K   27   6
In this article, I will explain how to implement Respository pattern and how to enable dependency injection feature to your MVC Application.

Introduction

This article discusses the usage of repository pattern with Autofac and  it shows how this pattern can be used with Autofac in MVC application 

Every application needs to access data from one or  the other source so, the best approach is to write  data access code in main application using repository pattern which act as a layer between business logic and data access layer  .In other words, repository isolates all data access code from rest of the application.

 

 

In Diag A 

as you see all controller methods are directly interacting to EntityFramework and that interacts with database .

in this approach,

1.There will be more duplication of code 

for example : if  application is modifying an entity from two diffrent controllers then there will be same repetion of code in both controller methods.

2.Future modifications 

for example : if there is a future modification for a database operation .  we need to modify code at all places other places wherever that same operation is taking place 

3.Not a Proper design 

combining business logic with data acces is not a good approach.

 

In Diag B.

controller methods interacts with customer repository so, no controller method will directly interacts  with EntityFramework  data context directly .

in this approach,

1. single point of change

for example :  if there is any change in future  you just need to make it at one place i.e repository as all business logic according to requirement will be written in respective methods .

 

Prerequisite

1.Visual studio 2013 

2.NorthwindDatabase if you dont have download .bak file from (http://northwinddatabase.codeplex.com/releases/view/71634) and restore it. Watch this video for restoring it (https://www.youtube.com/watch?v=lAvU0QT-OT0).

3.SQL Server: 2012.

4.MVC-5

5.Autofac libraries (online from Nuget)

6.Autofac Integration MVC libraries (online from Nuget)

7.Entity Frame work libraries as we shall store data using repository pattern (Online from Nuget)

Using the code

lets first create the project structure

i have two folders in my solution 

1.Data Access Layer

2. Web

Data Access Layer - In this there are three projects 

Web - This is MVC project 

Lets come to Data Access Layer Folder . There are 3 projects under it and all of them are of class library type.

1. Repository_Database - This project would be containing our  Entity framework.

2. Repository_RepoClasses - This project would be our repository classes that contains logic for interacting with database.

3.Repository_RepoInterfaces- This Project will include interface for repository classes that mentioned in Repository_RepoClasses project.

before this please ensure that you would have restored NORTHWIND database

Repository_Databae -right click -> add -> NewItem -> on left side click Data -> select ado.net entity data Model -> select Generate from Database () -> then select northwind databse that you restored() 

select yes to include path in connection string  from radio button options.

either you can  create edmx for whole database or for the only table that you need in our case we will be using customer table but making edmx for whole northwind database.

your edmx would look like this if you only select customer table.

create the interface for Northwind_DBEntities class(this is auto generated under .context.tt) by  right clicking -> selecting refactor -> extract interface.

 

override Save method of DbContext .

Second project :

RepositoryPattern_RepoClasses 

Add a class and give it name CustomerRepository.cs

C++
    public class CustomerRepository : ICustomerRepository
    {
        INorthwind_DBEntities NorthwindContext;
        public CustomerRepository(INorthwind_DBEntities db)
        {
            NorthwindContext = db;
        }
        public IEnumerable<Customer> SelectAll()
        {
         return NorthwindContext.Customers.ToList();
        }

        public Customer SelectByID(string id)
        {
        return NorthwindContext.Customers.Find(id);
        }

        public void Insert(Customer obj)
        {
            NorthwindContext.Customers.Add(obj);
        }
        public void Delete(string id)
        {
            var value = NorthwindContext.Customers.Where(i => i.CustomerID == id).FirstOrDefault();
            NorthwindContext.Customers.Remove(value);
        }
        public void Save()
        {
            NorthwindContext.SaveChanges();
        }
    }
}

Third Project:

RepositoryPattern_RepoInterfaces:

In this we will create the interface for all of the classes that we built in second project

C++
public interface ICustomerRepository
    {
        IEnumerable<Customer> SelectAll();
        Customer SelectByID(string id);
        void Insert(Customer obj);
        void Delete(string id);
        void Save();
    }

 

lets come to Web folder 

rightclick -> select add new project ->select web from left pane -> select asp.net application give it a name ->

then checkMVC and select empty as shown in below figure ..

it will create mvc application for you. 

in that project from nuget add autofac and entityframework dll as shown.

 

  

Add a controller to controller folder by right clicking ->add mvc controller 

then create a view for it.

and in your controller write this code.

C++
public class CustomerController : Controller
   {
       ICustomerRepository _CustomerRepo;

       public CustomerController(ICustomerRepository customerRepo)
       {
           _CustomerRepo = customerRepo;
       }

       //
       // GET: /Customer/
       public ActionResult Index()
       {
           List<Customer> model = (List<Customer>)_CustomerRepo.SelectAll();
           return View(model);
       }

       public ActionResult Insert(Customer obj)
       {
           _CustomerRepo.Insert(obj);
           _CustomerRepo.Save();
           return View();
       }

       public ActionResult Edit(string id)
       {
           Customer existing = _CustomerRepo.SelectByID(id);
           return View(existing);
       }

       public ActionResult ConfirmDelete(string id)
       {
           Customer existing = _CustomerRepo.SelectByID(id);
           return View(existing);
       }

       public ActionResult Delete(string id)
       {
           _CustomerRepo.Delete(id);
           _CustomerRepo.Save();
           return View();
       }

   }

In AppStart add a file named as AutofacConfig.cs make it a static class

C++
public static class AutofacConfig
   {
       public static void RegisterComponents()
       {
           var builder = new ContainerBuilder();
           builder.RegisterType<CustomerRepository>().As<ICustomerRepository>();
           builder.RegisterType<CustomerController>();
           builder.RegisterType<Northwind_DBEntities>().As<INorthwind_DBEntities>();
           var container = builder.Build();
           DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
       }

   }

and call this class method in Global.asax

in AutofacConfig what we have done.

we are registering our classes and its service resolver as, you can see we register our customer repository class to IcustomerRepository. 

it means whenever we use ICustomerRepository it will refer to CustomerRepository.cs  as, you can see above to this code in customer controller we used,

 
C++
ICustomerRepository _CustomerRepo;

public CustomerController(ICustomerRepository customerRepo)
{
    _CustomerRepo = customerRepo;
}

 

if we did not have called autofac.Registercomponets method in global.asax it would give an error saying parameterless constructor is required in cutomercontroller.

To learn more on autofac you can refer (http://autofac.org/)

C++
public class Application : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AutofacConfig.RegisterComponents();
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);

    }
}

now you can build the solution and create view for customer controller methods and use them.

you can refer to the whole source code.. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
3 pillarglobal
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionMissing line "No parameterless constructor defined for this object" Pin
Member 282696125-Nov-14 7:17
Member 282696125-Nov-14 7:17 
SuggestionWriting and style guide Pin
Vaso Elias25-Nov-14 6:38
Vaso Elias25-Nov-14 6:38 
QuestionAll images are missing Pin
Tridip Bhattacharjee19-Nov-14 20:23
professionalTridip Bhattacharjee19-Nov-14 20:23 
AnswerRe: All images are missing Pin
Vaso Elias25-Nov-14 6:42
Vaso Elias25-Nov-14 6:42 
SuggestionPlease Update Image Pin
Sandeep Singh Shekhawat19-Nov-14 19:33
professionalSandeep Singh Shekhawat19-Nov-14 19:33 
QuestionImages Pin
David_Wimbley19-Nov-14 17:35
professionalDavid_Wimbley19-Nov-14 17:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.