Why middleware in ASP.NET Core requires specific semantics, but not an interface?

The Invoke method is flexible and you can ask for additional parameters. ASP.NET will inject the additional parameters using the application's service configuration.

public async Task Invoke(HttpContext ctx, 
                         IHostingEnvironment host,
                         ISomethingElse service)
{
    // ...
}

C# interface definitions can't provide this flexibility in a nice way.


Since AspNetCore2.0 you can set middleware which implements interface IMiddleware.

public class InterfaceMiddleware : IMiddleware
{
    private InterfaceMiddlewareOptions _opts;

    public InterfaceMiddleware(IOptions<InterfaceMiddlewareOptions> opts)
    {
        _opts = opts.Value;
    }

    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        await context.Response.WriteAsync(_opts.Message);
    }
}

In addition to app.UseMiddleware<InterfaceMiddleware>(). You need to register your middleware in DI(singleton lifetime is not required).

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<InterfaceMiddlewareOptions>(opts =>
    {
        opts.Message = "IMiddleware interface is implemented";
    });

    services.AddSingleton<InterfaceMiddleware>();
}