如何在.Net Core 3 Worker服务中设置应用程序设置


22

我一直在寻找有关阅读.Net Core 3中的appsettings.json 的许多教程和SO问题(例如App Settings .Net Core),在处理Worker服务时,我找不到任何有关操作方法的指针。没有启动方法。相反,我有一个带有main方法的Program.cs:

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) =>
            {
                services.AddHostedService<Worker>();
            });
}

如何从.Net Core 3的Worker服务项目中的appsettings.json文件读取?

我添加了对使用.Net v4.8和另一个项目创建的自定义WCF客户端的引用,该项目仅在整个解决方案之间共享所有Busines域对象。我的解决方案主要是.Net v4.8,我想使用Worker Service。客户端项目通过代码在内部创建WCF客户端,因此所有绑定和端点都是可配置的。如果这是一个.Net v4.8项目,则将以下内容添加到app.config中:

<appSettings>
    ...
    <add key="AminServiceUri" value="http://localhost:45108/ServiceHost/v1/AminService.svc" />
    <add key="BillServiceUri" value="http://localhost:45108/ServiceHost/v1/BillService.svc" />
    <add key="CustomerServiceUri" value="http://localhost:45108/ServiceHost/v1/CustomerService.svc" />
    <add key="EpayServiceUri" value="http://localhost:45108/ServiceHost/v1/EpayService.svc" />
    <add key="FinanceServiceUri" value="http://localhost:45108/ServiceHost/v1/FinanceService.svc" />
    <add key="GrpServiceUri" value="http://localhost:45108/ServiceHost/v1/GrpService.svc" />
    <add key="MetaServiceUri" value="http://localhost:45108/ServiceHost/v1/MetaService.svc" />
    <add key="ReportServiceUri" value="http://localhost:45108/ServiceHost/v1/ReportService.svc" />
    <add key="ServiceInfoServiceUri" value="http://localhost:45108/ServiceHost/v1/ServiceInfoService.svc" />
    <add key="UsersServiceUri" value="http://localhost:45108/ServiceHost/v1/UsersService.svc" />
    ...
    <add key="ExcessiveLogging" value="false" />
    ...
</appSettings>

现在,我需要这些设置为新的JSON格式并读取它们。

编辑

这是一个新项目。工人没有做任何事情:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> logger;

    public Worker(ILogger<Worker> logger)
    {
        this.logger = logger;
    }

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

这是我如何获得此项目类型的方法:

工人服务

Answers:


36

例如,如果工人阶级需要访问存储在您的应用程序中的某些数据

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) {
            //do something that uses options

            logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(5000, stoppingToken);
        }
    }
}

在哪里WorkerOptions存储您的配置值。

public class WorkerOptions {
    public string AminServiceUri { get; set; }
    public string BillServiceUri { get; set; }

    //... other properties
}

假设appsettings.json文件具有相应的密钥

{
  "WCF": {
    "AminServiceUri":"http://localhost:45108/ServiceHost/v1/AminService.svc",
    "BillServiceUri":"http://localhost:45108/ServiceHost/v1/BillService.svc",

    //...other key-value pairs
  },
  "Logging": {
    "ExcessiveLogging": false
  }

}

默认情况下Host.CreateDefaultBuilder将设置常规配置(appsettings.json等)。

使用hostContext.Configuration以获得IConfiguration可用于访问所需的设置并添加强类型对象模型,它的实例。将该对象添加到服务集合中,以便可以在需要时将其注入

例如

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>();
            });
}

在创建工作程序时,将以其必需的依赖项对其进行注入。

ASP.NET Core中的参考配置


这个答案是如此完美。它提供了从应用程序设置中读取数据的正确方法。
Vighnesh

您可以使用IConfiguration而不是创建自定义类
Shimon Lebovits
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.