OWIN (Open Web Interface for .NET) is a simpler model for composing web-based applications without tying the application to the web server. To do this, a concept of “middleware” is used to create a pipeline through which requests travel.

Due to the differences in the way OWIN handles the application pipeline (detecting when a request starts/ends, etc.) integrating Autofac into an OWIN application is slightly different than the way it gets integrated into more “standard” ASP.NET apps. You can read about OWIN and how it works on this overview.

The important thing to remember is that order of OWIN middleware registration matters. Middleware gets processed in order of registration, like a chain, so you need to register foundational things (like Autofac middleware) first.

Normally when you register OWIN middleware with your application, you use the extension methods that come with the middleware. For example Web API has the app.UseWebApi(config); extension. Middleware registered in this fashion is statically defined and will not have dependencies injected.

For custom middleware, you can allow Autofac to inject dependencies into the middleware by registering it with your application container rather than registering it with a static extension.

varbuilder=newContainerBuilder();builder.RegisterType<MyCustomMiddleware>();//...varcontainer=builder.Build();// This will add the Autofac middleware as well as the middleware// registered in the container.app.UseAutofacMiddleware(container);

When you call app.UseAutofacMiddleware(container); the Autofac middleware itself will be added to the pipeline, after which any Microsoft.Owin.OwinMiddleware classes registered with the container will also be added to the pipeline.

Middleware registered in this way will be resolved from the request lifetime scope for each request passing through the OWIN pipeline.

For a simple scenario, app.UseAutofacMiddleware(container); will handle both adding an Autofac lifetime to the OWIN request scope as well as adding middleware that is registered with Autofac into the pipeline.

If you want more control over when DI-enabled middleware is added to the pipeline, you can use the UseAutofacLifetimeScopeInjector and UseMiddlewareFromContainer extensions.

varbuilder=newContainerBuilder();builder.RegisterType<MyCustomMiddleware>();//...varcontainer=builder.Build();// This adds ONLY the Autofac lifetime scope to the pipeline.app.UseAutofacLifetimeScopeInjector(container);// Now you can add middleware from the container into the pipeline// wherever you like. For example, this adds custom DI-enabled middleware// AFTER the Web API middleware/handling.app.UseWebApi(config);app.UseMiddlewareFromContainer<MyCustomMiddleware>();