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/

Published Sunday, April 01, 2012 5:29 AM by shiju

Comments

# Dependency Injection in ASP.NET Web API using Autofac

Sunday, April 01, 2012 6:22 AM by DotNetKicks.com

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# Dependency Injection in ASP.NET Web API using Autofac - Shiju Varghese's Blog | asp.net mvc | Scoop.it

Pingback from  Dependency Injection in ASP.NET Web API using Autofac - Shiju Varghese's Blog | asp.net mvc | Scoop.it

# The Morning Brew - Chris Alcock &raquo; The Morning Brew #1077

Pingback from  The Morning Brew - Chris Alcock  &raquo; The Morning Brew #1077

# ??????Autofac???ASP.NET Web API????????????????????? | ??????X??????

Pingback from  ??????Autofac???ASP.NET Web API????????????????????? | ??????X??????

# friday links 24 &laquo; A Programmer with Microsoft tools

Thursday, April 05, 2012 10:23 PM by friday links 24 « A Programmer with Microsoft tools

Pingback from  friday links 24 &laquo; A Programmer with Microsoft tools

# re: Dependency Injection in ASP.NET Web API using Autofac

Saturday, April 07, 2012 9:28 AM by micle77

Great Article

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

# re: Dependency Injection in ASP.NET Web API using Autofac

Tuesday, April 17, 2012 7:46 PM by Raul Macias

Very informative

# Dependency Injection in ASP.NET Web API using Autofac | Geekness in Words

Pingback from  Dependency Injection in ASP.NET Web API using Autofac | Geekness in Words

# re: Dependency Injection in ASP.NET Web API using Autofac

Wednesday, May 30, 2012 4:44 PM by Chris

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.

# re: Dependency Injection in ASP.NET Web API using Autofac

Monday, June 04, 2012 5:03 AM by Kate

I simply could not depart your website before

suggesting that I extremely enjoyed the usual information an individual provide

in your visitors? Is gonna be back incessantly in order to check out new posts

# re: Dependency Injection in ASP.NET Web API using Autofac

Friday, June 15, 2012 2:03 AM by Hudson

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.

# re: Dependency Injection in ASP.NET Web API using Autofac

Thursday, August 16, 2012 11:04 AM by to

Can http://efmvc.codeplex.com/ will be updated to release version of MVC4 and EF5?

# re: Dependency Injection in ASP.NET Web API using Autofac

Friday, August 17, 2012 2:08 AM by shiju

I will update the http://efmvc.codeplex.com/ app to working with ASP.NET MVC 4 and latest versions of Autofac and EF

# re: Dependency Injection in ASP.NET Web API using Autofac

Sunday, December 30, 2012 12:25 PM by Flagg

You should take part in a contest for one of the greatest sites on the net.

I most certainly will recommend this blog!

Leave a Comment

(required) 
(required) 
(optional)
(required)