Dependency Injection in ASP.NET Web API using Autofac

In this post, I will demonstrate how to use Dependency Injection in ASP.NET Web API using Autofac in an ASP.NET MVC 4 app. The new ASP.NET Web API is a great framework for building HTTP services. The Autofac IoC container provides the better integration with ASP.NET Web API for applying dependency injection. The NuGet package Autofac.WebApi provides the  Dependency Injection support for ASP.NET Web API services.

Using Autofac in ASP.NET Web API

The following command in the Package Manager console will install Autofac.WebApi package into your ASP.NET Web API application.

PM > Install-Package Autofac.WebApi

image

The following code block imports the necessary namespaces for using Autofact.WebApi

using Autofac;
using Autofac.Integration.WebApi;

The following code in the Bootstrapper class configures the Autofac.

   1:  public static class Bootstrapper
   2:  {
   3:   public static void Run()
   4:   {
   5:       SetAutofacWebAPI();
   6:   }       
   7:   private static void SetAutofacWebAPI()
   8:   {
   9:      var configuration = GlobalConfiguration.Configuration;
  10:      var builder = new ContainerBuilder();
  11:      // Configure the container 
  12:      builder.ConfigureWebApi(configuration);
  13:      // Register API controllers using assembly scanning.
  14:      builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
  15:      builder.RegisterType<DefaultCommandBus>().As<ICommandBus>()
  16:          .InstancePerApiRequest();
  17:      builder.RegisterType<UnitOfWork>().As<IUnitOfWork>()
  18:          .InstancePerApiRequest();
  19:      builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>()
  20:          .InstancePerApiRequest();
  21:      builder.RegisterAssemblyTypes(typeof(CategoryRepository)
  22:     .Assembly).Where(t => t.Name.EndsWith("Repository"))
  23:      .AsImplementedInterfaces().InstancePerApiRequest();
  24:      var services = Assembly.Load("EFMVC.Domain");
  25:      builder.RegisterAssemblyTypes(services)
  26:      .AsClosedTypesOf(typeof(ICommandHandler<>))
  27:          .InstancePerApiRequest();
  28:      builder.RegisterAssemblyTypes(services)
  29:      .AsClosedTypesOf(typeof(IValidationHandler<>))
  30:          .InstancePerApiRequest();
  31:      var container = builder.Build();
  32:      // Set the WebApi dependency resolver.
  33:      var resolver = new AutofacWebApiDependencyResolver(container);
  34:      configuration.ServiceResolver.SetResolver(resolver);             
  35:   }
  36:  }

The RegisterApiControllers method will scan the given assembly and register the all ApiController classes. This method will look for types that derive from IHttpController with name convention end with “Controller”. The InstancePerApiRequest method specifies the life time of the component for once per API controller invocation. The GlobalConfiguration.Configuration provides a ServiceResolver class which can be use set dependency resolver for ASP.NET Web API. In our example, we are using AutofacWebApiDependencyResolver class provided by Autofac.WebApi to set the dependency resolver.

The Run method of Bootstrapper class is calling from Application_Start method of Global.asax.cs.

   1:  protected void Application_Start()
   2:  {
   3:      AreaRegistration.RegisterAllAreas();
   4:      RegisterGlobalFilters(GlobalFilters.Filters);
   5:      RegisterRoutes(RouteTable.Routes);
   6:      BundleTable.Bundles.RegisterTemplateBundles();
   7:      //Call Autofac DI configurations
   8:      Bootstrapper.Run();
   9:  } 

Autofac.Mvc4

The Autofac framework’s integration with ASP.NET MVC has updated for ASP.NET MVC 4. The NuGet package Autofac.Mvc4 provides the dependency injection support for ASP.NET MVC 4. There is not any syntax change between Autofac.Mvc3 and Autofac.Mvc4

Source Code

I have updated my EFMVC app with Autofac.WebApi for applying dependency injection for it’s ASP.NET Web API services. EFMVC app also updated to Autofac.Mvc4 for it’s ASP.NET MVC 4 web app. The above code sample is taken from the EFMVC app. You can download the source code of EFMVC app from http://efmvc.codeplex.com/

4 Comments

  • Great Article

    We can also submit our .net related article links on http://www.dotnettechy.com to increase traffic

  • What about using Autofac with standard controllers and web api controllers in the same project? Setting the dependency resolver to one leaves the other out of the picture.

  • I'm really impressed with your writing skills and also with the layout on your blog. Is this a paid theme or did you customize it yourself? Anyway keep up the nice quality writing, it is rare to see a great blog like this one today.

  • You should take part in a contest for one of the greatest sites on the net.
    I most certainly will recommend this blog!

Comments have been disabled for this content.