newtonsoft json .net core 3.1 workerservice code example
Example: read configuration workerservice
public class Program {
public static void Main(string[] args) {
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) => {
IConfiguration configuration = hostContext.Configuration;
WorkerOptions options = configuration
.GetSection("WCF")
.Get<WorkerOptions>();
services.AddSingleton(options);
services.AddHostedService<Worker>();
});
}
public class Worker : BackgroundService {
private readonly ILogger<Worker> logger;
private readonly WorkerOptions options;
public Worker(ILogger<Worker> logger, WorkerOptions options) {
this.logger = logger;
this.options = options;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested) {
logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(5000, stoppingToken);
}
}
}
public class WorkerOptions {
public string AminServiceUri { get; set; }
public string BillServiceUri { get; set; }
}
{
"WCF": {
"AminServiceUri":"http://localhost:45108/ServiceHost/v1/AminService.svc",
"BillServiceUri":"http://localhost:45108/ServiceHost/v1/BillService.svc",
},
"Logging": {
"ExcessiveLogging": false
}
}