Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .Net Core 3.1辅助服务使用Appsettings.json_C#_Asp.net Core_Service Worker - Fatal编程技术网

C# .Net Core 3.1辅助服务使用Appsettings.json

C# .Net Core 3.1辅助服务使用Appsettings.json,c#,asp.net-core,service-worker,C#,Asp.net Core,Service Worker,我正在尝试从appsettings.json中获取我的应用程序设置,以用于我的worker服务(我只是假设这是正确的做法)。到目前为止,我还不知道如何使用Worker.cs中的appsettings 这是我在Program.cs中的内容 public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .Conf

我正在尝试从appsettings.json中获取我的应用程序设置,以用于我的worker服务(我只是假设这是正确的做法)。到目前为止,我还不知道如何使用Worker.cs中的appsettings

这是我在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>();
                });
公共静态IHostBuilder CreateHostBuilder(字符串[]args)=>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((主机上下文,配置)=>
{
//在此处配置应用程序。
配置
.SetBasePath(环境.CurrentDirectory)
.AddJsonFile(“appsettings.json”,可选:true,重载更改:true)
.AddJsonFile($“appsettings.{hostContext.HostingEnvironment.Environment Name}.json”,可选:true);
config.AddEnvironmentVariables();
})
.ConfigureServices((主机上下文,服务)=>
{
services.AddHttpClient();
services.AddHostedService();
});
添加工人阶级

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);
        }
public class Worker:BackgroundService
{
私有常量int ThreadDelay=5000;
专用只读ILogger\u记录器;
私有只读HttpClientu HttpClient;
私有只读JsonSerializer\u序列化程序;
公共工作者(ILogger记录器,IHttpClientFactory httpClient)
{
_记录器=记录器;
_httpClient=httpClient.CreateClient();
_serializer=新的JsonSerializer();
}
受保护的覆盖异步任务ExecuteAsync(CancellationToken stoppingToken)
{
同时(!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation(“在:{time}运行的工作进程”,DateTimeOffset.Now);
var位置=GetLocations(stoppingToken);
foreach(位置中的var项目)
{
}
//让我们在5分钟后再次启动线程
等待任务。延迟(ThreadDelay,stoppingToken);
}
}
私有字符串GetLocations(CancellationToken stoppingToken)
{
var result=string.Empty;
var response=\u httpClient.GetAsync($“https://”,stoppingToken);
返回结果;
}
专用异步任务TriggerPoll(CancellationToken stoppingToken)
{
var response=await\u httpClient.GetAsync($“https://”,stoppingToken);
}

看起来除了在
工作者
构造函数中需要一个
IConfiguration
实例之外,您还需要什么,所以框架的依赖项注入容器将提供它

在下面的小更改之后,从appsettings中获取如下值:
\u配置[“key”]

public class Worker:BackgroundService
{
私有常量int ThreadDelay=5000;
专用只读IConfiguration\u配置;
专用只读ILogger\u记录器;
私有只读HttpClientu HttpClient;
私有只读JsonSerializer\u序列化程序;
公共工作者(IConfiguration配置、ILogger记录器、IHttpClientFactory httpClient)
{
_配置=配置;
_记录器=记录器;
_httpClient=httpClient.CreateClient();
_serializer=新的JsonSerializer();
}
...
}

您能展示工人阶级吗?继续并添加了@egnomerator