简体   繁体   中英

.Net Core 3.1 Worker Service use Appsettings.json

I am trying to get my application settings out of appsettings.json for my worker service (I'm just assuming this is the correct thing to do). I have only gotten so far but can't actually figure out how to use the appsettings in the Worker.cs

Here is what I have in Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostContext, config) =>
                {
                    // Configure the app here.
                    config
                        .SetBasePath(Environment.CurrentDirectory)
                        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                        .AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true);

                    config.AddEnvironmentVariables();
                })
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHttpClient();
                    services.AddHostedService<Worker>();
                });

adding worker class

public class Worker : BackgroundService
    {
        private const int ThreadDelay = 5000;

        private readonly ILogger<Worker> _logger;
        private readonly HttpClient _httpClient;
        private readonly JsonSerializer _serializer;

        public Worker(ILogger<Worker> logger, IHttpClientFactory httpClient)
        {
            _logger = logger;
            _httpClient = httpClient.CreateClient();
            _serializer = new JsonSerializer();
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

                var locations = GetLocations(stoppingToken);

                foreach(var item in locations)
                {

                }


                //lets start the thread again in 5 minutes
                await Task.Delay(ThreadDelay, stoppingToken);
            }
        }

        private string GetLocations(CancellationToken stoppingToken)
        {
            var result = string.Empty;

            var response = _httpClient.GetAsync($"https://", stoppingToken);


            return result;
        }

        private async Task TriggerPoll(CancellationToken stoppingToken)
        {
            var response = await _httpClient.GetAsync($"https://", stoppingToken);
        }

It looks like you have what you need other than requiring an IConfiguration instance in your Worker constructor so the framework's dependency injection container will provide it.

After the minor changes below, get a value out of appsettings like this: _configuration["key"]

public class Worker : BackgroundService
{
        private const int ThreadDelay = 5000;

        private readonly IConfiguration _configuration;
        private readonly ILogger<Worker> _logger;
        private readonly HttpClient _httpClient;
        private readonly JsonSerializer _serializer;

        public Worker(IConfiguration configuration, ILogger<Worker> logger, IHttpClientFactory httpClient)
        {
            _configuration = configuration;
            _logger = logger;
            _httpClient = httpClient.CreateClient();
            _serializer = new JsonSerializer();
        }

        ...

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM