System.AggregateException In Worker project Dot Net 8

  Kiến thức lập trình

I am trying to implement a windows service by using worker project with communication to a SQL Server database.
ON sunning it. I am getting Two exceptions :

System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: TTRWindowWorkerService.TTRService.TTRReportService: Cannot consume scoped service TTRWindowWorkerService.TTRRepository.ITTRReportRepository from singleton Microsoft.Extensions.Hosting.IHostedService.

InvalidOperationException: Cannot consume scoped service TTRWindowWorkerService.TTRRepository.ITTRReportRepository from singleton Microsoft.Extensions.Hosting.IHostedService.

This is my Program.cs :

 var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json").Build();

 IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices(services => {  
                    services.AddDbContext<SWMdbContext>(opt => { 
                        opt.UseSqlServer(configuration.GetConnectionString("SWMP2Database"));
                      }); 
                       services.AddScoped<ITTRReportRepository,TTRReportRepository>();
                       services.AddHostedService<TTRReportService>();
                 })
         .UseWindowsService()
         .Build();

  await host.RunAsync();

What I am doing wrong Can anyone explain me? I didn’t find any solution for it.

I tried to make a windows service by using background services of Worker project. There I call a dbContext from a library project and try to insert the data into a table in very minute by using LINQ but my project is not even starting its giving me exception. I tried to use singleton but it is also now working.

New contributor

Anas Nabi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT