Download Sample Application

Table of Contents

  1. What is AutoFac?
  2. AutoFac demo (MVC 3, C#) 
  3. InstanceScope  

What is AutoFac?

Autofac helps in implementing dependency injection (DI) or Inversion of control (IoC) in Microsoft .net environments. To know more about dependency injection please follow the link:

http://en.wikipedia.org/wiki/Dependency_injection

You can get the AutoFac associated dlls from ‘NuGet’.

AutoFac demo (MVC 3, C#):

Here, I am demoing an MVC3 application in which we will be creating an instance of the class ‘Test’ which is implementing an interface ‘ITest’ using AutoFac.

The definition of ‘Test’ class is below and it’s implementing its interface Members (GetEvenNumbers, GetSmallestNNumbers)

public class Test : ITest

    {

        List<int> integers = new List<int>() { 1, 2, 4, 5, 6, 8, 10, 11, 13, 14, 15, 19, 29, 91 };

         publicIEnumerable<int> GetEvenNumbers()

        {

            IList<int> result = new List<int>();

            foreach (var i in integers)

            { 

               if (i % 2 == 0)

                 {

                    result.Add(i);

                 }

            }

            return result;

        }

        publicIEnumerable<int> GetSmallestNNumbers(int count)

        {

            List<int> result = integers;

            result.Sort();

            return result.Take(count);

        } 

    }

 

This class is implementing Interface ‘ITest’ and definition of this interface is as:

public interface ITest

    {

         IEnumerable<int> GetEvenNumbers();

         IEnumerable<int> GetSmallestNNumbers(int count);

    }

Instance of ‘Test’ class is created by AutoFac and the corresponding registry is done in Application_Start() method of Global.asax file . The same
registry can also be done in some config file, for more information please
visit –
https://code.google.com/p/autofac/wiki/XmlConfiguration

 The associated code Global.asax is:

        protected void Application_Start()

        {

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);

            RegisterRoutes(RouteTable.Routes);

            //Autofac work – start

            var builder = new ContainerBuilder();

            builder.RegisterType<Test>().As<ITest>();

            builder.RegisterType<HomeController>();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));

            //AutoFac work – End

          }

Here ‘Test’ class is resolved as ‘ITest’ and ‘Test’ can only be used by ‘ITest’ (I will show later how we can achieve this).

Also, HomeController(or other controllers) is registered in ‘AutoFac’ and we can get the instance of this controller using ‘AutoFac’.

 The required code to access the controllers via AutoFac is explained below: 

  public class ControllerActivator : IControllerActivator

    {

        public IController Create(RequestContext requestContext, Type controllerType)

        {

            Object controller = DependencyResolver.Current.GetService(controllerType);

            var scope = AutofacDependencyResolver.Current.RequestLifetimeScope;

            if (controller != null)

            {

                scope.InjectProperties(controller);

               return (IController)controller;

            }

            throw new HttpException(404, String.Format(“The service ‘{0}’ with controller ‘{1}’ in path ‘{2}’ has not been registered.”controllerType.FullName, controllerType.FullName,requestContext.HttpContext.Request.Path));

         }

    }

 This  ‘ControllerActivator’ class is implementing an interface  ‘IControllerActivator’. This interface is in AutoFac dll and the definition of this interface below. And from the Summary of this interface we can sum that implementation of this interface helps in instantiating controllers using ‘AutoFac’. 

#region Assembly System.Web.Mvc.dll, v4.0.30319

// c:\Program Files (x86)\Microsoft
ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll

#endregion 

using System;

using System.Web.Routing;

namespace System.Web.Mvc

{

    // Summary:

    //  Provides fine-grained control over how controllers are instantiated using

    //  dependency injection.

    public interface IControllerActivator

    {

        // Summary:

        // When implemented in a class, creates a controller.

        //

        // Parameters:

        //   requestContext:

        //     The request context.

        //

        //   controllerType:

        //     The controller type.

        //

        // Returns:

        //     The created controller.

        IController Create(RequestContext requestContext, Type controllerType);

    }

}

Below is the HomeController code and you can see how we are getting the instance of ‘Test’ class using ‘ITest’ interface without using new keyword.

public class HomeController : Controller

    {

        private ITest _test; 

        public HomeController(ITest test)

        { 

           _test = test; 

        }

         publicActionResult Index()

        {

            var evenNumbersList = _test.GetEvenNumbers();

            var smallestNNumbersList = _test.GetSmallestNNumbers(5); 

            string evenNumbers = string.Empty;

            string smallestNNumbers = string.Empty; 

            foreach (var evenNumber in evenNumbersList)

            {

                 evenNumbers += evenNumber.ToString() + “,”;

            }

            foreach (var smallestNumber in smallestNNumbersList)

            {

                 smallestNNumbers += smallestNumber.ToString() + “,”;

            }

            ViewBag.AutoFacMsg = “Amazing Autofac Demo”;

            ViewBag.EvenNumebrs = “Even Numbers: “ + evenNumbers;

            ViewBag.SmallestNNumbers = “Smallest N numbers: “ + smallestNNumbers;

            return View();

        }

        publicActionResult About()

        {           

            return View();

        }

     }

Here, whenever the HomeController is requested, instance of class ‘Test’ is created through AutoFac and same can be accessed through ‘ITest’ interface. 

public HomeController (ITest test)

{

   _test = test;

}

 And then we can access the ‘Test’ class methods i.e. GetEvenNumbers() and GetSmallestNNumbers() using ‘ITest’ interface. Here whenever we call

HomeController a new instance of class ‘Test’ is created. Below I am trying to explain different instance creation rules in AutoFac. 

InstanceScope 

Instance scope determines how an instance is shared between requests for the same service. 

Autofac can create a single instance (single instance for every request/call), a new instance (always new instance
is created for every request/call) or a single instance within some kind of context, e.g. a thread or an HTTP request (per lifetime scope.)

Instance Per Dependency

Using this, a new instance will be returned from each request for a class. 

builder.RegisterType<ClassName>().InstancePerDependecy();

 

Single Instance

Helps us in achieving singleton design pattern.

builder.RegisterType<ClassName>().SingleInstance(); 

Instance per Lifetime Scope

Using this we can create instances per-request, per-transaction or per-thread. So, same instance will be returned in the same
thread or request or per-thread.

builder.RegisterType<ClassName>().InstancePerMatchingLifetimeScope(); 

Download Sample Application 

References:

1.https://code.google.com/p/autofac/
2.  http://en.wikipedia.org/wiki/Dependency_injection
3.  http://en.wikipedia.org/wiki/Autofac