Dependency injection not working with Owin self-hosted Web Api 2 and Autofac

前端 未结 1 1824
臣服心动
臣服心动 2020-12-14 16:40

I\'m finding my feet with Web Api 2, Owin and Autofac and need some guidance, please.

Overview
I have an Owin self-hosted Web Api that uses Auto

相关标签:
1条回答
  • 2020-12-14 17:13

    You should be using the HttpConfiguration with which you're bootstrapping OWIN everywhere. So, this:

    GlobalConfiguration.Configuration.DependencyResolver = resolver;
    

    Should become:

    config.DependencyResolver = resolver;
    

    Other than that, everything looks good. Api controllers are registered, although you're not giving them a scope. Not sure if in Autofac scoping defaults to per-request for controllers or if it has the notion of per-request scoping at all (I know that LightInject has it).

    Looking around, I think you followed the example on the Google Code repo for Autofac, which indeed uses GlobalConfiguration. Instead, if you look at the GitHub example, it is a bit different. Try to make the changes according to this. Including this:

    // This should be the first middleware added to the IAppBuilder.
    app.UseAutofacMiddleware(container);
    

    2016 update

    What I said above still applies, but something extra from Autofac's docs (thanks Brad):

    A common error in OWIN integration is use of the GlobalConfiguration.Configuration. In OWIN you create the configuration from scratch. You should not reference GlobalConfiguration.Configuration anywhere when using the OWIN integration.

    0 讨论(0)
提交回复
热议问题