60

Is it possible to configure Autofac to work with ASP .NET MVC and ASP .NET Web Api. I'm aware that the dependency resolvers are different. But when using the documented approaches I can only set one global resolver.

// Set the dependency resolver implementation.
GlobalConfiguration.Configuration.DependencyResolver = resolver;

Is this approach bad idea? Should I separate my solution into two projects and handle the dependency injection for each individually?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Raúl Roa
  • 12,061
  • 13
  • 49
  • 64
  • I have a minimal implementation here: http://byterot.blogspot.co.uk/2012/04/aspnet-web-api-series-part-4-dependency.html – Aliostad Jul 14 '12 at 16:49

3 Answers3

98

It is certainly possible to configure Autofac to work with both MVC and Web API. This is expected to be a very common scenario. There are two separate dependency resolver implementations because MVC and Web API can be used independently of one another. The same applies for the Autofac integrations.

When using both MVC and Web API in the same application each will require its own dependency resolver, though they can be provided with the same instance of the container.

var builder = new ContainerBuilder();

// Add your registrations

var container = builder.Build();

// Set the dependency resolver for Web API.
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

// Set the dependency resolver for MVC.
var mvcResolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(mvcResolver);

It is also possible to share registrations between the two because the InstancePerApiRequest and InstancePerHttpRequest lifetime scopes now share the same tag.

Note that the mechanism for setting the dependency resolver for Web API and MVC is different. Web API uses GlobalConfiguration.Configuration.DependencyResolver and MVC uses DependencyResolver.SetResolver.

Alex Meyer-Gleaves
  • 3,821
  • 21
  • 11
  • Great answer. The only thing is about "because MVC and Web API can be used independently of one another.". I reckon autofac has two plugins for mvc and webapi separately because the two have different runtime. – anIBMer Jun 17 '13 at 05:17
  • 1
    WebApi does not use `GlobalConfiguration` per say, rather it uses `HttpConfiguration` which in the case of owin-based projects can be simply instantiated and used thusly: `config.DependencyResolver = new AutofacWebApiDependencyResolver(...)`. – Crescent Fresh Apr 26 '16 at 15:49
14

I thought I'd add a little help those struggling with this in mvc5 and web api 2.

First add nuget packages

  • Autofac
  • Autofac asp.net mvc 5 integration
  • Autofac asp.net web api 2.x integration

in global add in application_start (or as app_start class) add call to the below class

AutofacConfig.RegisterAutoFac();

now add this class under App_start

using System.Reflection;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;

namespace Example1.Web
{
    public class AutofacConfig
    {
        public static IContainer RegisterAutoFac()
        {
            var builder = new ContainerBuilder();

            AddMvcRegistrations(builder);
            AddRegisterations(builder);

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            return container;
        }

        private static void AddMvcRegistrations(ContainerBuilder builder)
        {
            //mvc
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinderProvider();

            //web api
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            builder.RegisterModule<AutofacWebTypesModule>();
        }

        private static void AddRegisterations(ContainerBuilder builder)
        {
            //builder.RegisterModule(new MyCustomerWebAutoFacModule());
        }
    }
}

From now for each new assembly you add to the project add a new module and then register the module in the AddRegisterations function (example given)

Note:

I returned the container, this isn't necessary.

This scans the current assembly for modules so don't add local modules in AddRegisterations otherwise you will register everything twice.

Choco Smith
  • 1,658
  • 18
  • 24
  • 2
    thankyou. Finally someone that just lays it out here i na simple an easy to understand way without imposing opinions etc. – punkologist Mar 23 '15 at 21:35
4

Definitely separate them. Autofac has both ASP.NET MVC and ASP.NET Web API integrations. This is not always the case but if you need the same services in both application, most probably there is something wrong with the application architecture.

Here is how you might do this with ASP.NET Web API:

internal class AutofacWebAPI {

    public static void Initialize(HttpConfiguration config) {

        config.DependencyResolver = new AutofacWebApiDependencyResolver(
            RegisterServices(new ContainerBuilder())
        );
    }

    private static IContainer RegisterServices(ContainerBuilder builder) {

        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).PropertiesAutowired();

        //deal with your dependencies here
        builder.RegisterType<CarsService>().As<ICarsService>();
        builder.RegisterType<CarsCountService>().As<ICarsCountService>();

        return builder.Build();
    }
}

Then, register this inside the Global.asax.cs as below:

AutofacWebAPI.Initialize(GlobalConfiguration.Configuration);
tugberk
  • 57,477
  • 67
  • 243
  • 335