Cannot resolve scoped service from root provider when "ASPNETCORE_ENVIRONMENT": "Development"

Viewed 5742

I'm getting exception when trying to resolve service like this IApplicationBuilder.ApplicationServices.GetServices<AdminPanelDbContext>(); and "ASPNETCORE_ENVIRONMENT": "Development" is set to development.

Exception:

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

but when i set "ASPNETCORE_ENVIRONMENT": "Production" everything works fine.

I looked under appsettnings.Development.json and there is nothing different from appsettings.json. Is there any other setting that is affecting this?

1 Answers

See 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.

This feature is new in ASP.NET Core v3. Previous versions of ASP.NET Core lacked this feature.

To me, the downside of this feature is that it is actually disabled by default when you run in production. It should have been on by default in all environments, because it will cause multi-threading issues and memory leaks.

Related