Contact List using MVC5, AngularJS and Redis: Part 2 - Install and Configure AutoFac

Introduction

This article walks you through the steps to configure AutoFac (dependency injection) on a  MVC + WebApi project.

 

STEP 1 - Install Nuget

The first step is to add Autofac references to your project.

So on the Visual Studio 2013, select the follow menu option:

  • Tools-> Library Package manager -> Manage NuGet Packages for Solutio
  • Search for AutoFac and select the options that are checked on the follow image. And select the option Install

 

This option will install the Nuget Package.

 

On our project we are using owin integration, so we also need to install dependencies of Autofac to owin.

  • Search for "autofac owin", and install Autofac Asp.NET MVC 5.1 Owin Integration and Autofac ASP.NET WebApi2.2 Owin integration.

 

STEP 2 - Configure Startup file

After we install all necessary packages, we need to configure our startup project:

 

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Owin;
using Owin;
using System.Web.Mvc;
using System.Web.Http;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using System.Reflection;
using System.Configuration;
using ServiceStack.Redis;
using Services;
 
[assembly: OwinStartup(typeof(AngularJS.Startup))]
 
namespace AngularJS
{
    public partial  class Startup
    {
        public void  Configuration(IAppBuilder app)
        {
            //Register dependencies with Autofac
            var container = RegisterServices();
 
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
 
            GlobalConfiguration.Configuration.DependencyResolver = new  AutofacWebApiDependencyResolver(container);
 
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(GlobalConfiguration.Configuration);
            app.UseAutofacMvc();
        }
 
        private IContainer RegisterServices()
        {
            var builder = new  ContainerBuilder();
 
            //MVC
            builder.RegisterControllers(typeof(MVCApplication).Assembly);
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinderProvider();
            builder.RegisterModule<AutofacWebTypesModule>();
            builder.RegisterSource(new ViewRegistrationSource());
            builder.RegisterFilterProvider();
 
            //WebApi
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
 
            return builder.Build();
        }
    }
}

  

Resources