title: Dependency injection not working with Owin self-hosted Web Api 2 and Autofac
body: <p>I'm finding my feet with Web Api 2, Owin and Autofac and need some guidance, please.</p>
  
  <p><strong>Overview</strong><br>
  I have an Owin self-hosted Web Api that uses Autofac for IoC and dependency injection. The project is a console app acting like a service, meaning it can be stopped and started. I have an Authentication controller with two constructors: one parameter-less and the other injects a repository. </p>
  
  <p><strong>Problem</strong><br>
  When I run the service and call the api, my parameter-less constructor is called and my repository never gets injected (_repository = null).</p>
  
  <p><strong>Research</strong><br>
  I've done a fair bit of research and found some helpful projects on Github, which I replicated to the tee but I'm missing a big part of the puzzle. <a href="https://code.google.com/p/autofac/wiki/WebApiIntegration" rel="noreferrer">This</a> was helpful but didn't solve my problem. I read <a href="https://stackoverflow.com/questions/24403618/how-to-integrate-autofac-with-wepapi-2-and-owin">this question</a> on Stack Overflow and Dane Sparza had a nice <a href="https://github.com/danesparza/OWIN-WebAPI-Service" rel="noreferrer">demo project</a> but I couldn't find a clear solution. The problem is not the self-hosting but the dependency injection.</p>
  
  <p><strong>My code</strong> (thinned out for explanation)  </p>
  
  <pre><code>public class Startup
  {
      public void Configuration(IAppBuilder app)
      {
          HttpConfiguration config = new HttpConfiguration();
  
          config.Routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );
  
          var json = config.Formatters.JsonFormatter;
          json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
          config.Formatters.Remove(config.Formatters.XmlFormatter);
  
          var connectioninfo = ConnectionInfo.FromAppConfig("mongodb");
  
          var builder = new ContainerBuilder();                                    // Create the container builder.
          builder.RegisterApiControllers(Assembly.GetExecutingAssembly());         // Register the Web API controllers.
          builder.Register(c =&gt; new Logger()).As&lt;ILogger&gt;().InstancePerRequest();  // Register a logger service to be used by the controller and middleware.
          builder.RegisterType&lt;AuthenticationRepository&gt;().As&lt;IAuthenticationRepository&gt;().WithParameter(new NamedParameter("connectionInfo", connectioninfo)).InstancePerRequest();
  
          var container = builder.Build();
  
          var resolver = new AutofacWebApiDependencyResolver(container);           // Create an assign a dependency resolver for Web API to use.
          GlobalConfiguration.Configuration.DependencyResolver = resolver;         // Configure Web API with the dependency resolver
  
          app.UseCors(CorsOptions.AllowAll);  
          app.UseWebApi(config);
          app.UseAutofacWebApi(config);  // Make sure the Autofac lifetime scope is passed to Web API.
      }
  </code></pre>
  
  <p>Program.cs</p>
  
  <pre><code> static void Main(string[] args)
      {           
          var service = new ApiService(typeof(Program), args);
  
          var baseAddress = "http://localhost:9000/";
          IDisposable _server = null;
  
          service.Run(
             delegate()
             {
                 _server = WebApp.Start&lt;Startup&gt;(url: baseAddress);
             },
             delegate()
             {
                 if (_server != null)
                 {
                     _server.Dispose();
                 }
             }
         );
      }
  </code></pre>
  
  <p>ApiController</p>
  
  <pre><code>public class AuthenticationController : ApiController
  {
      private IAuthenticationRepository _repository;
  
      public AuthenticationController() { }
  
      public AuthenticationController(IAuthenticationRepository repository)
      {
          _repository = repository;
      }
  
      [AllowAnonymous]
      public IHttpActionResult Authenticate(string name, string password)
      {
          if (_repository == null)
              return BadRequest("User repository is null.");
  
          var valid = _repository.AuthenticateUser(name, password);
          return Ok(valid);
      }
  }
  </code></pre>