简体   繁体   中英

Dependency Injection Error in Worker Service

Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: ProjectName.WS.Worker': Cannot consume scoped service 'ProjectName.Service.IServiceManager' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.)

Program.cs Code

IHost host = Host.CreateDefaultBuilder(args)
.UseWindowsService(options =>
{
    options.ServiceName = "Service Name";
})
.ConfigureLogging(logging =>
{
    logging.AddSerilog();

})
.ConfigureServices((builder, services) =>
{
    services.AddHostedService<Worker>(); 
    services.AddDbContext<AppDbContext>(options =>
       options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))
   );

    services.AddIdentity<IdentityUser, IdentityRole>().AddDefaultTokenProviders()
        .AddEntityFrameworkStores<AppDbContext>(); 
     
    services.AddScoped<IServiceManager, ServiceManager>();
    services.AddScoped<IRepoManager, RepoManager>();  

})
.Build();

await host.RunAsync();

Worker.cs file Code

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger; 
    private readonly IServiceManager _serviceManager;
    private readonly IRepoManager _repoManager;

    public Worker(ILogger<Worker> logger, IServiceManager serviceManager, IRepoManager repoManager)
    {
        _logger = logger; 
        _serviceManager = serviceManager;
        _repoManager = repoManager;
            
    } 
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var ewr = _serviceManager.CountryService.GetAll(); 
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(1000, stoppingToken);
        }
    }
}

Service Manager File Code --

public class ServiceManager : IServiceManager
{
    private IRepoManager _repoManager { get; set; }
    public ServiceManager(IRepoManager repoManager)
    {
        _repoManager = repoManager; 
        CountryService = new CountryService(_repoManager.CountryRepo); 
    } 
    public ICountryService CountryService { get; set; } 
}

Remo Manager File Code --

public class RepoManager : IRepoManager
{
    private AppDbContext _db;

    public RepoManager(AppDbContext db)
    {
        _db = db; 
        CountryRepo = new CountryRepo(_db); 
    } 
    public ICountryRepo CountryRepo { get; private set; } 
}

Country Service File Code --

     public class CountryService : ICountryService
    {
        private readonly ICountryRepo _repo;
        public CountryService(ICountryRepo repo)
        {
            _repo = repo;
        }
   }

Country Repo File Code --

public class CountryRepo : ICountryRepo
{
    private readonly AppDbContext _db;
    public CountryRepo(AppDbContext db)
    {
        _db = db;
    }
}

AppDBContext file code --

    public class AppDbContext : IdentityDbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }
        public DbSet<Country> Country { get; set; }
   }

The service can not be initialized using the constructor instead you should do it like this:

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            using (IServiceScope scope = _serviceProvider.CreateScope())
            {
                var _localServiceManager = scope.ServiceProvider.GetRequiredService<IServiceManager>();
                var ewr = _serviceManager.CountryService.GetAll();
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);
            }
        }
    }

This is an example of microsoft

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM