2

I have a WebAPI Controller which has a dependency on another class:

 public class HealthCheckController : System.Web.Http.ApiController
    {
        private readonly IHealthCheckReport _healthCheckReport;

        public HealthCheckController(IHealthCheckReport healthCheckReport)
        {
            this._healthCheckReport = healthCheckReport;
        }
}

I'm using Autofac and inside the Register method of my WebApiConfig class, I've added:

 var builder = new ContainerBuilder();
 builder.RegisterType<HealthCheckReport>().As<IHealthCheckReport>();
 var container = builder.Build();

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

But when I call the Index() action, it complains that my controller doesn't have a default constructor. Whereas, I expected Autofac just magically inject the type I have registered above.

How should this be configured?

tereško
  • 58,060
  • 25
  • 98
  • 150
The Light
  • 26,341
  • 62
  • 176
  • 258

1 Answers1

2

You need to register the api controller too.

  builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

Source: http://code.google.com/p/autofac/wiki/WebApiIntegration

Chris Diver
  • 19,362
  • 4
  • 47
  • 58