I saw some code lilke this:
public class CustomMiddleware {
private RequestDelegate next;
public CustomMiddleware (RequestDelegate nextDelegate) {
next = nextDelegate;
}
public async Task Invoke(HttpContext context, IResponseFormatter formatter) {
...
await next(context);
}
}
and IResponseFormatter service is registered as:
public void ConfigureServices(IServiceCollection services) {
services.AddTransient<IResponseFormatter, GuidService>();
}
I know how DI works, but my understanding how middleware works is, next
(RequestDelegate
) represents the next middleware's Invoke
method, so in CustomMiddleware, even the second argument is resolved by DI, but the definition of RequestDelegate
is
public delegate Task RequestDelegate(HttpContext context);
how does the previous middleware before CustomMiddleware
knows that CustomMiddleware
's Invoke
method has changed by having an extra argument? It cannot know in advance, therefore the previous middleware's next
RequestDelegate
does't match the signature of CustomMiddleware
's Invoke
method?