'Worker Service Error while validating the service descriptor ServiceType
I have a worker service that I wrote in .Net Core 3.1. Here I want to register services in another layer (ICarVerticalLogic and IEmailPdfLogic) in my program.cs, but when I run the project I get the following error.
My Program.cs
public class Program
{
public static void Main(string[] args)
{
var startupPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule?.FileName);
var logFilePath = Path.Combine(startupPath, "logs", "logs.txt");
Log.Logger = new LoggerConfiguration()
.WriteTo.File(logFilePath, rollingInterval: RollingInterval.Day)
.CreateLogger();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureLogging(logging =>
{
logging.AddSerilog();
})
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton(AutoMapperConfig.CreateMapper());
services.AddScoped<ICarVerticalLogic, CarVerticalLogic>();
services.AddScoped<IEmailPdfLogic, EmailPdfLogic>();
services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
services.AddEntityFrameworkSqlServer()
.AddDbContext<AsamDbContext>(options =>
{
options.UseMySql(hostContext.Configuration.GetSection("ConnectionString").Value);
});
services.AddHostedService<Worker>();
});
}
Error :
InvalidOperationException: Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: CarVerticalWorkerService.Worker': Cannot consume scoped service 'Asam.Logic.Infrastructure.ICarVerticalLogic' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.
Solution 1:[1]
The worker service is a singleton service by default. And a scoped service instances are bound to request. You can not inject a scoped service into a singleton service.
If you don't mind change the lifetime of ICarVerticalLogic and IEmailPdfLogic service
to Singleton, try to modify your codes:
services.AddScoped<ICarVerticalLogic, CarVerticalLogic>();
services.AddScoped<IEmailPdfLogic, EmailPdfLogic>();
to
services.AddSingleton<ICarVerticalLogic, CarVerticalLogic>();
services.AddSingleton<IEmailPdfLogic, EmailPdfLogic>();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

