5

I just updated all my Autofac packages to the latest to get support for web api 2. In my api controller I have set up a constructor asking for an instance of a service layer class, this is identical to how I use autofac with all my mvc controllers and it works fine.

In my ioc config that is executed at app start I have registered the web api controller.

builder.RegisterType<UsersApiController>().InstancePerApiRequest();

I also tried

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

But autofac is not working with my api controller, the constructor that asks for the service class to be injected does not even get executed. I also get an error if I do not include a default parameter less constructor on the api controller.

Is there a known issue with web api 2 and auto fac or am I missing something?

JBeckton
  • 7,095
  • 13
  • 51
  • 71
  • 2
    Have you set the `GlobalConfiguration.Configuration.DependencyResolver`? – nemesv Jan 12 '14 at 16:46
  • like this? DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); – JBeckton Jan 12 '14 at 20:56
  • My mvc controllers work as expected with DI, wondering why the API controllers are not. – JBeckton Jan 12 '14 at 20:57
  • 3
    No that is the MVC DependencyResolver. The WepAPI looks like this: `var resolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = resolver;` https://code.google.com/p/autofac/wiki/WebApiIntegration – nemesv Jan 12 '14 at 20:58
  • possible duplicate of [MVC Web API RTM not working with Autofac Integration](http://stackoverflow.com/questions/12276913/mvc-web-api-rtm-not-working-with-autofac-integration) – nemesv Jan 12 '14 at 21:13
  • Hey thanks... I missed that step, I was hoping it was something simple.. copy your comments as an answer if you would like credit for helping me out. – JBeckton Jan 12 '14 at 21:53

1 Answers1

-1

This blog worked for me

http://danielhindrikes.se/cloud/azure/azure-mobile-services-and-autofac/

So my code now looks is

public static void Register(){

            ConfigOptions options = new ConfigOptions();

            //Prepare Dependency Injection Container
            var configBuilder = new ConfigBuilder(options, DependencyInjectionConfig);


            // Use this class to set WebAPI configuration options
            HttpConfiguration config = ServiceConfig.Initialize(configBuilder);
}

private static void DependencyInjectionConfig(ContainerBuilder containerBuilder)
{
            containerBuilder.Register(component => new EFProductRepository()).As<IProductRepository>().SingleInstance();
            containerBuilder.RegisterType<ProductsManager>().As<IProductsManager>();
}
Sebastian Pakieła
  • 2,970
  • 1
  • 16
  • 24