Bob
Bob

Reputation: 16551

Why do I only get scoped service resolution errors in Development environments?

I am aware that the cause of the error described below is that I need a scope to instantiate the service, which can be accomplished with Services.CreateScope() and the matching .Dispose()/using. The question is why I get different behaviour in dev and prod environments.


I have a .NET Core 3.1 console application that uses the .NET Generic Host for dependency injection. Within it, I have an EF Core DbContext defined as a scoped service for database access using AddDbContext, as below:

var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((hostContext, services) =>
    {
        var configuration = hostContext.Configuration;

        services
            .AddDbContext<BotDbContext>(options =>
            {
                options
                    .UseLazyLoadingProxies()
                    .UseSqlite(configuration.GetConnectionString("Database"));
            });
    });
var db = host.Services.GetRequiredService<BotDbContext>();

Initially, I was testing this with the environment (DOTNET_ENVIRONMENT) as Production, as is the default. Everything worked.

I wanted a separate Development environment, to closer mimic the default ASP.NET Core templates. To do this, I defined a debug-time environment variable DOTNET_ENVIRONMENT=Development.

As soon as I did that, I received the following exception:

System.InvalidOperationException: 'Cannot resolve scoped service 'MyNamespace.Data.BotDbContext' from root provider.'

Why does this exception only happen when the environment is Development, but not Production?

Upvotes: 6

Views: 1258

Answers (1)

Bob
Bob

Reputation: 16551

You have created your host using CreateDefaultBuilder. Looking more closely at the documentation, we can see one of the default configuration items:

enables scope validation on the dependency injection container when EnvironmentName is 'Development'

We can also see in the source code that it sets ValidateScopes on the ServiceProvider only in Development environments.

With this configuration, outside Development environments the configured ServiceProvider will happily return scoped services outside of scoped contexts (though this should never be relied upon; those services are scoped for a reason!).

Upvotes: 12

Related Questions