我在尝试解决这样的服务时遇到异常 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.json
和appsettings.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/