无法构造某些服务-验证辅助服务.Net Core 3.1(依赖项注入)中的服务描述符时出错

无法构造某些服务-验证辅助服务.Net Core 3.1(依赖项注入)中的服务描述符时出错,.net,.net-core,dependency-injection,service,worker,.net,.net Core,Dependency Injection,Service,Worker,在.Net Core 3.1中创建辅助服务。辅助服务中引用的业务逻辑 在业务逻辑中,我使用Db上下文 public class CountryService : ICountryService { private readonly projectDbContext _dbContext; public CountryService (projectDbContext dbContext) { _dbCo

在.Net Core 3.1中创建辅助服务。辅助服务中引用的业务逻辑

在业务逻辑中,我使用Db上下文

      public class CountryService : ICountryService {
            private readonly projectDbContext _dbContext;
            public CountryService (projectDbContext  dbContext) {
                _dbContext = dbContext;
            }
            // public CountryService(){

            // }
            public IEnumerable<object> GetCountrys () {
                try {
                            //Code
                     }
               Catch(System.Exception){
                   throw ex;
                    }
}

公共类CountryService:IContryService{
私有只读projectDbContext_dbContext;
公共国家服务(projectDbContext dbContext){
_dbContext=dbContext;
}
//公共服务(){
// }
公共IEnumerable GetCountrys(){
试一试{
//代码
}
捕获(系统异常){
掷骰子;
}
}
工人服务计划

         public static void Main (string[] args) {
            try {
                var builder = new ConfigurationBuilder ()
                    .SetBasePath (Directory.GetCurrentDirectory ()) //location of the exe file
                    .AddJsonFile ("appsettings.json", optional : true, reloadOnChange : true);

                IConfiguration Configuration = builder.Build ();

                CreateHostBuilder (args).ConfigureServices ((hostContext, services) => {
                    services.AddHostedService<Worker> ()
                        .Configure<EventLogSettings> (c => {
                            c.LogName = "Sample Service";
                            c.SourceName = "Sample Service Source";
                        });
                    services.AddScoped<ICountryService, CountryService> ();
                    //services.AddTransient<ICountryService> (_ => _.GetRequiredService<IOptions<ICountryService>> ().Value);
                    services.AddDbContext<iDepoDbContext> (options =>
                        options.UseNpgsql (Configuration.GetConnectionString ("PostGresqlDevConnection")));
                }).Build ().Run ();
            } catch (System.Exception ex) {
                throw ex;
            } 

        }
publicstaticvoidmain(字符串[]args){
试一试{
var builder=新配置生成器()
.SetBasePath(Directory.GetCurrentDirectory())//exe文件的位置
.AddJsonFile(“appsettings.json”,可选:true,reloadOnChange:true);
IConfiguration-Configuration=builder.Build();
CreateHostBuilder(args).ConfigureServices((主机上下文,服务)=>{
services.AddHostedService()
.Configure(c=>{
c、 LogName=“示例服务”;
c、 SourceName=“示例服务源”;
});
services.AddScoped();
//services.AddTransient(=>u.GetRequiredService().Value);
services.AddDbContext(选项=>
options.UseNpgsql(Configuration.GetConnectionString(“PostGresqlDevConnection”));
}).Build().Run();
}catch(System.Exception-ex){
掷骰子;
} 
}
工薪阶层

 public class Worker : BackgroundService {
        private readonly ILogger<Worker> _logger;
        private readonly ICountryService _countryService;

        public Worker (ICountryService countryService) {
            _countryService = countryService;
        }

        protected override async Task ExecuteAsync (CancellationToken stoppingToken) {
            try {
                while (!stoppingToken.IsCancellationRequested) {
                    // _logger.LogInformation ("Worker running at: {time}", DateTimeOffset.Now);
                    var countries = _countryService.GetCountrys ();
                    await Task.Delay (1000, stoppingToken);
                }
       } catch (System.Exception ex) {
                throw ex;
       }

        }
    }
public class Worker:BackgroundService{
专用只读ILogger\u记录器;
私人只读ICountryService\u countryService;
公共工作者(IContryService国家服务){
_countryService=countryService;
}
受保护的覆盖异步任务ExecuteAsync(CancellationToken stoppingToken){
试一试{
同时(!stoppingToken.IsCancellationRequested){
//_logger.LogInformation(“在:{time}运行的工作程序”,DateTimeOffset.Now);
var countries=\u countryService.GetCountrys();
等待任务。延迟(1000,停止待命);
}
}catch(System.Exception-ex){
掷骰子;
}
}
}
错误消息

“有些服务无法构建(验证服务描述符“ServiceType:Microsoft.Extensions.Hosting.IHostedService Lifetime:Singleton实现类型:ExcelUploadService.Worker”时出错:无法使用Singleton“Microsoft.Extensions.Hosting.IHostedService”中的作用域服务“iProjectWeb.Application.Interface.Master.Geography.IConryService”。)

private IServiceScopeFactory服务{get;}
公职人员(工厂服务部)
{
服务=服务;
}
受保护的覆盖异步任务ExecuteAsync(CancellationToken stoppingToken)
{
使用(var scope=Services.CreateScope())
{
var myScopedService=scope.GetRequiredService();
//…使用此处的服务。。。
}
}

您能提供一个完整的故障排除示例吗?我无法调试您的代码,部分原因是您没有定义ie“projectDbContext”。您的错误与我的错误相同(对于.net core 3.1 API程序),我通过确保所有必需的服务实际上都在程序启动时托管来修复它们。也许这个链接在这方面会有所帮助:
    private IServiceScopeFactory Services { get; }
    
    public Worker(IServiceScopeFactory services)
    {
        Services = services;
    }
    
    protected override async Task ExecuteAsync (CancellationToken stoppingToken)
    {
        using (var scope = Services.CreateScope())
        {
            var myScopedService = scope.GetRequiredService<ICountryService>();
            // ... Use the service here ...
        }
    }