Search code examples
interfaceasp.net-coreowinmiddlewareowin-middleware

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


As known, IApplicationBuilder of the method Configure (class Startup) in ASP.NET Core requires specific semantics (to have method 'Invoke' with input parameter of HttpContext type and Task as return value). But why it's not implemented as interface? I can write something like it:

public class FakeMiddleware
{

}

and register it:

    app.UseMiddleware<FakeMiddleware>();

and we'll get an runtime error. Of course, it's trivial thing and easy to be found and fix, but it's implemented so rough, without interface?


Solution

  • 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.