为什么ASP.NET Core中的中间件需要特定的语义而不需要接口? [英] Why middleware in ASP.NET Core requires specific semantics, but not an interface?

查看:158
本文介绍了为什么ASP.NET Core中的中间件需要特定的语义而不需要接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,ASP.NET Core中的Configure(类Startup)方法的IApplicationBuilder需要特定的语义(使方法"Invoke"的输入参数为HttpContext类型,而Task为返回值).但是为什么不将其实现为接口呢?我可以这样写:

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
{

}

并注册:

    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?

推荐答案

Invoke方法非常灵活,您可以要求其他参数. ASP.NET将使用应用程序的服务配置注入其他参数.

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#接口定义不能很好地提供这种灵活性.

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

这篇关于为什么ASP.NET Core中的中间件需要特定的语义而不需要接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆