C#
Файл Program.cs
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;
using MyWorkerServiceCore1.Options;
namespace MyWorkerServiceCore1
{
public class Program
{
public static string EventLogName = "My Worker Service1";
public static string EventLogSource = "My App1";
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(options => options.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Information))
.ConfigureServices((hostContext, services) =>
{
IConfiguration configuration = hostContext.Configuration;
services.Configure<ApplicationOptions>(configuration.GetSection("ApplicationOptions"));
services.AddHostedService<Worker>()
.Configure<EventLogSettings>(config =>
{
config.LogName = EventLogName;
config.SourceName = EventLogSource;
});
}).UseWindowsService();
}
}
Файл appsettings.json
{
"ApplicationOptions": {
"MyName": "Evgen"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
Создадим новую папку
Options вот так:
D:/MyWorkerServiceCore1/Options
Внутри
Options папки создадим новый файл
ApplicatioOptions.cs
В этом файле класс
ApplicatioOptions с параметром
MyName совпадает с секцией из файла
appsettings.json
Файл ApplicationOptions.cs
using System.Text;
namespace MyWorkerServiceCore1.Options
{
public class ApplicationOptions
{
public string MyName { get; set;}
}
}
Файл Worker.cs
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MyWorkerServiceCore1.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MyWorkerServiceCore1
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly ApplicationOptions _applicationOptions;
public Worker(ILogger<Worker> logger , IOptions<ApplicationOptions> options)
{
_logger = logger;
_applicationOptions = options.Value;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("User: " + _applicationOptions.MyName);
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
}