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?