Genato
Genato

Reputation: 606

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

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?

Upvotes: 14

Views: 13516

Answers (1)

Steven
Steven

Reputation: 172835

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 the current implementation is that this validation is actually disabled by default when you run in production. The validation should have been on by default in all environments, because ignoring the warning will cause multi-threading issues and memory leaks.

Upvotes: 23

Related Questions