This is a plugin that supports the dynamic manipulation of middleware while the application is running. The middleware is created the same way as the original, but registered differently.
First, install NuGet. Then, install Ltmonster.AspNetCore.DynamicMiddleware from the package manager console:
PM> Install-Package Ltmonster.AspNetCore.DynamicMiddleware
Or from the .NET CLI as:
dotnet add package Ltmonster.AspNetCore.DynamicMiddleware
First, write your middleware. As follows:
public sealed class Plugin1(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context)
{
Console.WriteLine("start plugin1");
await next(context);
Console.WriteLine("end plugin1");
}
}Then, register in Program.cs
builder.Services.AddDynamicMiddleware();
app.UseDynamicMiddleware()
.InstallPlugin<Plugin1>("Plugin1", "This is the first plugin");Finally, if you need to control at runtime dynamic middleware, please use DynamicMiddlewareContainer
var container = app.ApplicationServices.GetRequiredService<DynamicMiddlewareContainer>();
container.EnablePlugin("Plugin1");
container.DisablePlugin("Plugin1");
container.SetPluginOrder("Plugin1", 10);