ASP.Net Core 2 ServiceProviderOptions.ValidateScopes 属性

标签 asp.net asp.net-core asp.net-core-mvc

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/

相关文章:

asp.net-core - Asp.net Core 2.1 Identity 的 LockoutEnabled 属性的实际用途是什么?

reverse-engineering - Entity Framework 7 逆向工程不起作用

javascript - 如何将动态 HTML 表中输入的项目添加到模型绑定(bind)列表

asp.net - 如何将我的 ASP.NET 成员(member)数据库从 Express 更改为标准 SQL?

c# - 模型值在回发期间丢失

database - 如何在 ASP.NET Core 中使用 DbConfiguration 类

.net-core - 没有配置文件提供程序来处理提供的文件

asp.net-core-mvc - MVC 6 HttpPostedFileBase?

asp.net - 是否可以替换asp :button with a HTML element

Asp.net Mvc Ajax Json(后数组)