Reputation: 838
I have developed a .Net Core background service which was working fine both when running as a service and when debugging in Visual Studio.
Then the following error started happening but only when debugging in Visual Studio
Cannot consume scoped service myDbContext from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'"
On deployment the service does not experience the same problem.
I've read several posts saying to get around this by creating a scoped service, however if I set the project up on a different machine by getting the code from source control, the error doesn't happen.
I have deleted the project from the problem environment and pulled the code from source control again but the issue still arises.
To me this suggests it's an environment issue, rather than a coding one.
The basic code is below.
The issue arises at the line host.Run();
.
Does anyone have any pointers as to how to isolate the cause and therefore potentially find a fix?
Thanks
public class Program
{
public static void Main(string[] args)
{
var method = MethodBase.GetCurrentMethod();
var methodName = method.Name;
var type = method.DeclaringType;
Log.Information("{0}.{1}: Started.", type, methodName);
try
{
var isService = !(Debugger.IsAttached || args.Contains("--console"));
if (isService)
{
var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
Directory.SetCurrentDirectory(pathToContentRoot);
}
var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray());
var host = builder.Build();
if (isService)
{
host.RunAsWebCustomService();
}
else
{
host.Run();
}
return;
}
catch (Exception ex)
{
Log.Fatal(ex, "Error in {0{.{1}: {2}", type, methodName, ex.Message);
throw;
}
finally
{
Log.CloseAndFlush();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var method = MethodBase.GetCurrentMethod();
var methodName = method.Name;
var type = method.DeclaringType;
Log.Information("{0}.{1}:called", type, methodName);
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(AppContext.BaseDirectory))
.AddJsonFile("appsettings.json", optional: true);
var configuration = builder.Build();
var url = configuration["WebHostBuilder:Url"];
return WebHost.CreateDefaultBuilder(args)
.UseUrls(url)
.ConfigureServices(
(hostContext, services) =>{services.AddHostedService<Worker>();})
.UseStartup<Startup>()
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration));
}
}
Upvotes: 2
Views: 1510
Reputation: 46
I ran into the same problem when I specified the "Development" environment, but everything is normal in the "Production".
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"MyProject.Api": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Strange DI behaviour with ASPNETCORE_ENVIRONMENT
In development mode we run some extra validations as the container is built. The fact that you're seeing an error means that something is wrong.
Upvotes: 0
Reputation: 706
I have been working in dotnet core since 2 years and things that i found out is:-
Do not resolve a scoped service from a singleton. It may cause the service to have incorrect state when processing subsequent requests. It's fine to:
Resolve a singleton service from a scoped or transient service. Resolve a scoped service from another scoped or transient service. By default, in the development environment, resolving a service from another service with a longer lifetime throws an exception. For more information, Scope Validation
Upvotes: 2