How to Register Middleware in HostingStartup?

Viewed 661

background

I hope to add additional middleware by registering the plugin without changing the original project code, but how to get the IApplicationBuilder required to register the middleware in the plugin is the biggest problem I currently face.
According to the Hosting Startup Document, the plugin can be registered by inheriting IHostingStartup and loaded automatically when the project starts, E.g:

// plugin
public class MyStartup: IHostingStartup
{
     // Implement the IHostingStartup interface
     public void Configure(IWebHostBuilder builder)
     {
         // TODO: I want to get an IApplicationBuilder object to register middleware
     }
}

question

How to get IApplicationBuilder object by IWebHostBuilder?

1 Answers

In the official docs, Extend Startup with startup filters explains that IStartupFilter might be useful here:

Use IStartupFilter to configure middleware at the beginning or end of an app's Configure middleware pipeline without an explicit call to Use{Middleware}.

Here's a sample implementation:

public class MyStartupFilter : IStartupFilter
{
    public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
    {
        return app =>
        {
            app.UseMiddleware<MyMiddleware>();
            next(applicationBuilder);
        };
    }
}

In this example, we're adding MyMiddleware to the beginning of the pipeline, which means that it runs before the rest of the pipeline. To run MyMiddleware at the end of the pipeline, switch the order of app.UseMiddleware and next.

You must also register this implementation with the DI container, like this:

// plugin
public class MyStartup : IHostingStartup
{
     // Implement the IHostingStartup interface
     public void Configure(IWebHostBuilder builder)
     {
         builder.ConfigureServices(services =>
         {
             services.AddTransient<IStartupFilter, MyStartupFilter>();
         });
     }
}

Although this works, it's not as flexible as you might need it to be. For example, it doesn't allow you to inject middleware between middleware added by the app.

Related