一些服务无法构建 - 在Worker Service .Net Core 3.1(Dependency Injection)中验证服务描述符时出错。

3

.Net Core 3.1中创建Worker服务。在Worker服务中引用商业逻辑。

在商业逻辑中,我正在使用Db Context。

      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;
                    }
}

工作程序服务 Program.cs

         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;
            } 

        }

Worker.cs

 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;
       }

        }
    }

错误信息

"某些服务无法构建(验证服务描述符时出错:'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: ExcelUploadService.Worker': 无法从单例 'Microsoft.Extensions.Hosting.IHostedService' 中使用作用域服务 'iProjectWeb.Application.Interface.Master.Geography.ICountryService'。)"


你能提供一个完整的示例来进行故障排除吗?我无法调试你的代码,部分原因是你没有定义"projectDbContext"。你的错误与我的相同(针对 .net core 3.1 API 程序),我通过确保所有必需的服务实际上在程序启动时被托管来解决了这些问题。也许这个链接在这方面会有所帮助:https://andrewlock.net/new-in-asp-net-core-3-service-provider-validation/ - Fhyarnir
你有同样的问题吗?当作用域类需要注入dbContext时,会出现错误。你解决了吗? - Thomas Byrne
2个回答

1
    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 ...
        }
    }

0

.NET 6完整示例,包含后台服务

using HR.Data.Interface.UOW;

namespace HR.API.Backgrounds
{
    public sealed class OutgoingEmailService : BackgroundService
    {
        private readonly ILogger<OutgoingEmailService> _logger;
        private readonly IServiceScopeFactory _serviceScopeFactory;

        public OutgoingEmailService(IServiceScopeFactory serviceScopeFactory, ILogger<OutgoingEmailService> logger) => (_serviceScopeFactory, _logger) = (serviceScopeFactory, logger);

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("OutgoingEmailService.ExecuteAsync - Loop");

                using (var scope = _serviceScopeFactory.CreateScope())
                {
                    using (var unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>())
                    {
                        var test = unitOfWork.AuditLogService.Get(1);
                    }
                }

                await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
            }
        }
    }
}

这并没有展示一个需要注入的作用域类的例子 - "CountryService (projectDbContext dbContext)". - Thomas Byrne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接