Sunday, 3 July 2016

AutoFac 3.5 MVC 5.1 Implementation

> C#/.Net Samples


This article covers Dependency Injection using AutoFac. For more details check the official doc.

IoC Container structure should be built in such a way that it should be easy to maintain. For complex applications, with layered structure, delegate the building of different parts to each project.

We'll use AutoFac Module to achieve this. Since this is a simple application and my Interface and the Class are sitting in the main project, i have used local binder.

Project Setup


Class & Interface

I have created a very simple "User" class with just one method. This class implements "IUser".


App_Binding: AutoFacBinding.cs

  •  AutoFacBinding is responsible for registering the dependencies. 
  • This class inherits from Module
  • Overrides the Load method
  • Takes the instance of ContainerBuilder


IoC Container

We'll place the hook in Global.asax, Application_Start method



AutoFac Config


We'll need to register different items like controllers and model binders while building the AutoFac Container. Check the official doc for each section in the above code. 

Controller DI

We'll use the constructor injection in our controller.

Note: we are using the interface rather than the concrete class. The biggest advantage is with utnit testing.

Filter DI

Filter uses property injection. Reference the above code for CustmActionFilter...