Using Autofac in a ASP.NET MVC 4 application

Posted by – October 18, 2012

ASP.NET MVC is a great framework, very flexible, but sometimes we need to organize a little better our business logic, there’s nothing better than have a business logic completely decoupled from controller, which can be easily reused on several controllers over the project.

To help ASP.NET MVC make use of reusable business logic and other logic components aswell, we can add a DI/IoC container to our project, after few days researching about IoC container alternatives, I choose Autofac to create my first web application that takes advantage of Dependency Injection.

First of all, add Autofac assemblies to your project, for this I used Nuget like below:

Now I just add the autofac configuration on Web.config:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  <configSections>
    <!-- We need this to be able to configure AutoFac -->
    <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/>
  </configSections>
  <!--Configuring components to be injected by Autofac -->
  <autofac defaultAssembly="MyAutofac">
    <components>
      <component
             type="MyAutofac.Services.ProductService, MyAutofac">
        <properties>
          <!-- Injecting a value on Name property of ProductService -->
          <property name="Name" value="Bombom" />
        </properties>
      </component>
    </components>
  </autofac>

In other to initialize the Autofac container in my web app I added the following code to my Global.asax:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
        protected void Application_Start()
        {
            var builder = new ContainerBuilder();

            builder.RegisterSource(new ViewRegistrationSource());

            //Register HomeController and autowire components on its properties
            builder.RegisterType<HomeController>().InstancePerHttpRequest()
                .PropertiesAutowired();

            //Lê componentes da seção autofac no web.conf, lá está configurado o ProductsService
            builder.RegisterModule(new ConfigurationSettingsReader("autofac"));

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
     
            //Remaing code...
        }

ProductService is just a POCO which contains a property called “Name”, the value of this property is injected via web.config, here’s how he is defined:

1
2
3
4
5
6
7
8
9
10
11
12
13
namespace MyAutofac.Services
{
    public class ProductService
    {
        //The value of this property will be injected by autofac
        public string Name { get; set; }

        public string Execute()
        {
            return Name;
        }
    }
}

With autofac properly configured and ProductService ready to be used, we will need to create the controller, since we are autowiring the service to controller, we must have a property on which the service instance is injected like below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace MyAutofac.Controllers
{
    public class HomeController : Controller
    {

        //ProductService instance will be inject by autofac, we need this property
        public ProductService Service { get; set; }

        //
        // GET: /Home/

        public ActionResult Index()
        {
            ViewBag.Message = Service.Execute();
            return View();
        }

    }
}

When you load up the page on webbrowser, the HomeController is initialized, Autofac instantiate ProductService and inject the “Bombom” value on Name property, the service instance is now injected on HomeController view Service property and then de Index action is called, we just call the Execute method of Product service which returns “Bombom” as result, the string is now printed on page.

Share

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>