gpt4 book ai didi

asp.net-core - "When using a scoped service, inject the service into the Invoke or InvokeAsync"是什么意思?

转载 作者:行者123 更新时间:2023-12-04 02:50:06 26 4
gpt4 key购买 nike

我正在阅读.Net Core 中关于 DI 的 MS 文档。

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2

我遇到了线

"Warning

When using a scoped service in a middleware, inject the service into the Invoke or InvokeAsync method. Don't inject via constructor injection because it forces the service to behave like a singleton."



任何人,请解释一下这是什么意思?

然后这里投票最多的答案之一是使用构造函数 DI 注入(inject)来进行范围服务。
AddTransient, AddScoped and AddSingleton Services Differences?

最佳答案

这记录在 ASP.NET Core 中间件中:Per-request dependencies .

因为中间件是在应用程序启动时构建的,而不是按请求构建的,所以中间件构造函数使用的作用域生命周期服务不会在每个请求期间与其他依赖注入(inject)类型共享。如果您必须在中间件和其他类型之间共享范围服务,请将这些服务添加到 Invoke 方法的签名中。 Invoke 方法可以接受由 DI 填充的其他参数:

public class CustomMiddleware
{
private readonly RequestDelegate _next;

public CustomMiddleware(RequestDelegate next)
{
_next = next;
}

// IMyScopedService is injected into Invoke
public async Task Invoke(HttpContext httpContext, IMyScopedService svc)
{
svc.MyProperty = 1000;
await _next(httpContext);
}
}

关于asp.net-core - "When using a scoped service, inject the service into the Invoke or InvokeAsync"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55449036/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com