How to integrate Autofac with WepApi 2 and Owin?

风流意气都作罢 提交于 2019-12-03 10:54:57

问题


I am using this package to integrate Autofac with my WebApi Owin application:

https://www.nuget.org/packages/Autofac.WebApi2.Owin

And following this post:

http://alexmg.com/owin-support-for-the-web-api-2-and-mvc-5-integrations-in-autofac/

My code in Startup.cs looks like this:

        var config = new HttpConfiguration();

        IContainer container = EngineContext.InitializeEngine();

        var dependencyResolver = new AutofacWebApiDependencyResolver(container);
        config.DependencyResolver = dependencyResolver;

        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);

        WebApiConfig.Register(config);
        app.UseWebApi(config);

However whichever way I spin it, rearrange the code or whatever, Autofac is just not able to resolve anything. Before Owin I had my Global.asax method working just fine:

    protected void Application_Start()
    {
        IContainer container = EngineContext.InitializeEngine();

        var dependencyResolver = new AutofacWebApiDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = dependencyResolver;

        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

What am I missing?

Thanks


回答1:


Ok,

I figured it out. The Autofac Owin integration actually creates an Owin liftimescope, which is available through the whole Owin pipeline, thus available to middleware and extends this lifetimescope to the HttpRequestMessage. This is the lifetimescope marked with the AutofacWebRequest tag.

So all the previous WebApi integration code still needs to be performed on application startup. I have included:

    var dependencyResolver = new AutofacWebApiDependencyResolver(container);
    config.DependencyResolver = dependencyResolver;

but missed:

var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).InstancePerRequest();

in the EngineContext.Initialize method, which does all the registrations via the builder.

Here you can find more information on how to integrate Autofac with the WebApi, which obviously needs to be done also in the case of Owin:

https://code.google.com/p/autofac/wiki/WebApiIntegration

I hope this is useful!



来源:https://stackoverflow.com/questions/24403618/how-to-integrate-autofac-with-wepapi-2-and-owin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!