Создание службы Worker в. Net Core 3.1. Присвоил Business Logi c в службе Worker.
В Business logi c я использую 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;
}
}
Worker Service 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 Время жизни: Singleton.