我正在编写一个中间件,该中间件需要注册一定范围的依赖项。有没有一种方法可以注册此中间件而不必将代码同时放入ConfigureServices
的{{1}}和Configure
方法中?
答案 0 :(得分:0)
不。服务和中间件不一样。而且,在DI容器知道之前,无法注入某些服务。换句话说,我们需要先注册这些服务,然后再将它们注入中间件。
您可以改为创建常规的中间件:
public class ConventionalMiddleware
{
private readonly RequestDelegate _next;
public ConventionalMiddleware(RequestDelegate next){
_next = next;
}
public async Task InvokeAsync(HttpContext context, Service1 s1, Service2 s2, ...)
{
// ...
}
}
和UseMiddleware<ConventionalMiddleware>()
中的Configure()
会增加体重。