c# - "ASPNETCORE_ENVIRONMENT": "Development" 时无法解析来自根提供程序的范围服务

标签 c# dependency-injection asp.net-core-3.1

我在尝试解决这样的服务时遇到异常 IApplicationBuilder.ApplicationServices.GetServices<AdminPanelDbContext>();"ASPNETCORE_ENVIRONMENT": "Development"设置为开发。
异常(exception):

Cannot resolve scoped service 'AdminPanel.DAL.DbContexts.AdminPanel.AdminPanelDbContext' from root provider.


但是当我设置 "ASPNETCORE_ENVIRONMENT": "Production"一切正常。
我看了下appsettnings.Development.jsonappsettings.json没什么区别.是否有任何其他设置会影响此设置?

最佳答案

Dependency injection in ASP.NET Core - Scope validation :

When the app runs in the Development environment and calls CreateDefaultBuilder to build the host, the default service provider performs checks to verify that:

  • Scoped services aren't resolved from the root service provider.
  • Scoped services aren't injected into singletons.

[...]

Scoped services are disposed by the container that created them. If a scoped service is created in the root container, the service's lifetime is effectively promoted to singleton because it's only disposed by the root container when the app shuts down. Validating service scopes catches these situations when BuildServiceProvider is called.

For more information, see Scope validation.


此功能是 ASP.NET Core v3 中的新增功能。以前版本的 ASP.NET Core 缺少此功能。
对我来说,这个功能的缺点是当你在生产中运行时它实际上是默认禁用的。它应该在所有环境中默认开启,因为它会导致多线程问题和内存泄漏。

关于c# - "ASPNETCORE_ENVIRONMENT": "Development" 时无法解析来自根提供程序的范围服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64055738/

相关文章:

Angular2 DI : Inject a new value on every injection?

asp.net-core - 在 ASPNET Core 中的路由中使用 ApiExplorerSettings GroupName

asp.net-core - ASP.Net Core 排除除英语以外的已发布语言目录

c# - 可执行文件因奇怪的异常而失败

c# - 在xaml中的按钮点击触发器上设置按钮内容

c# - 在 C# 2.0 中将 Dictionary<string,List<foo>> 转换为 List<foo>

asp.net-core - 为什么 blazor dotnet core 3.1 webassembly 客户端和共享项目是 netstandard 2.1?

c# - WCF:运行几秒钟后出现 EndpointNotFoundException

.net - 依赖注入(inject) - 分层应用程序

java - 根据 application.yml 中的属性使用 Spring Boot 进行注入(inject)