gpt4 book ai didi

ASP.Net Core 2 ServiceProviderOptions.ValidateScopes 属性

转载 作者:行者123 更新时间:2023-12-02 18:27:01 33 4
gpt4 key购买 nike

ServiceProviderOptions.ValidateScopes 到底是什么?我觉得我无法完全理解它在幕后的作用。我在教程中遇到过这个问题,但没有解释。

最佳答案

我假设您正在谈论这段代码:

services.BuildServiceProvider(new ServiceProviderOptions
{
ValidateScopes = true
});
// or
services.BuildServiceProvider(true); // or false

ASP.NET Core 提供程序有一个机制,可以验证单例容器是否解析了范围服务。 ASP.NET Core 有两种容器。主要的单例容器在应用程序的生命周期内有效,并且对每个请求都有作用域容器。

此选项将阻止从单例容器解析作用域服务,也就是说,如果您不小心尝试在 Configure 方法中解析作用域服务,您将收到异常。然而,如果您禁用它,则不应该禁用它。

public void Configure(IApplicationBuilder app)
{
// will throw exception, since by default DbContext is registered as scope
app.ApplicationServices.GetRequiredService<MyDbContext>();
}

异常类似于

InvalidOperationException: Cannot resolve 'IExampleService' from root provider because it requires scoped service 'MyDbContext'.

此行为是为了防止内存泄漏并解析单例容器中的作用域服务(应该是短期的),本质上使该服务也成为准单例(因为它们不会直到容器被释放为止,并且单例容器仅在应用程序关闭时被释放)。

在即 Configure 方法中解析范围服务的正确方法是这样的

// get scoped factory
var scopedFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
// create a scope
using (var scope = scopedFactory.CreateScope())
{
// then resolve the services and execute it
var context = scope.ServiceProvider.GetRequiredService<MyDbContext>();
}
// here, the child (scoped) container will be disposed and all scoped and transient services from it

更新 12/2020:The default value is now false for .NET 5.0 .

~~默认值为true~~,除非您确切地知道自己在做什么,否则您应该像这样保留它,否则您将面临由未发布的服务造成的严重内存泄漏(或对象已处理异常)的风险.

关于ASP.Net Core 2 ServiceProviderOptions.ValidateScopes 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50198609/

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