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

How to setup app settings in a .Net Core 3 Worker Service

我一直在查看许多关于在 .Net Core 3 中阅读 appsettings.json 的教程和 SO 问题(例如 ),但在处理时我找不到任何关于操作方法的指示与工人服务。没有启动方法。相反,我有一个 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 Service 项目中读取 appsettings.json 文件?

我添加了对我使用 .Net v4.8 创建的自定义 WCF 客户端的引用,以及另一个在整个解决方案之间共享所有业务域对象的项目。我的解决方案主要是 .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);
        }
    }
}

下面是我如何获得此项目类型:

例如,如果工作人员 class 需要访问存储在您的应用程序设置中的某些数据

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

创建工作程序时,将为其注入所需的依赖项。

引用Configuration in ASP.NET Core

继续尼科西的回答 也可以在ConfigureService方法中设置Startupclass中的选项,像这样:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
    
    public void ConfigureServices(IServiceCollection services)
    {
        // others services configuration
        WorkerOptions options = 
            Configuration.GetSection("WCF").Get<WorkerOptions>();

        services.AddSingleton(options);
        services.AddHostedService<Worker>();
    }
}

我是怎么做到的:

Progam.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) =>
            {
                IConfiguration configuration = hostContext.Configuration;
                services.Configure<RabbitMQConfiguration>(configuration.GetSection(nameof(RabbitMQConfiguration)));
                services.AddHostedService<Worker>();
            });
}

在您的工作器中,您可以访问如下选项:

public Worker(ILogger<Worker> logger, IOptions<RabbitMQConfiguration> options)
{
    _queue = options.Value.RabbitMQUrl;
    _options = options.Value;
    _logger = logger;
}

您还需要一个 class 作为您的选项对象:

public class RabbitMQConfiguration
{
    public string RabbitMQUrl { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
   // ...
}

在appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "RabbitMQConfiguration": {
    "RabbitMQUrl": "rabbitmq://yoururl",
    "Username": "admin",
    "Password": "mypassword",
  }
}