问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/40897781/why-middleware-in-asp-net-core-requires-specific-semantics-but-not-an-interface