Search code examples
asp.net-mvcautofacowin-middleware

Use pipeline stage marker for autofac middleware


I register a per-request lifetime middleware (it has some dependecies) in autofac

builder.RegisterType<RequestLocaleSetter>().InstancePerRequest();

Then I register all autofac middleware at startup.cs

        app.UseAutofacMiddleware(resolver.ApplicationContainer);
        app.UseAutofacMvc();

I can set a pipeline stage for middleware registered in startup.cs like

        app.Use(typeof(RequestLocaleSetter));
        app.UseStageMarker(PipelineStage.PostAcquireState);

How can I do it for a certain autofac-registered middleware?


Solution

  • From autofac docs: http://docs.autofac.org/en/latest/integration/owin.html#controlling-middleware-order

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

     var builder = new ContainerBuilder();
     builder.RegisterType<MyCustomMiddleware>(); //... var container =
     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>();