gpt4 book ai didi

c# - 将 appsettings 配置 DI 添加到 HostBuilder 控制台应用程序

转载 作者:行者123 更新时间:2023-12-02 03:04:49 39 4
gpt4 key购买 nike

我尝试在使用 HostBuilder 的 .NET Core 控制台应用程序中包含 appsettings.json 文件,并尝试添加一个部分 (AppVars)配置。当我尝试执行此操作时,出现错误:

System.InvalidOperationException: Unable to resolve service for type AppVars while attempting to activate...

这是我的代码:

private static async Task Main(string[] args)
{
var isService = !(Debugger.IsAttached || args.Contains("--console"));

var config1 = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true)
.Build();

var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<FileWriterService>();

services.Configure<AppVars>(config1.GetSection("AppVars"));

});

//...
}

下面我尝试在类中注入(inject) AppVars:

public class FileWriterService : IHostedService, IDisposable
{
private const string Path = @"d:\TestApplication.txt";

private Timer _timer;
private AppVars _appVars;
public FileWriterService(AppVars appVars)
{
//_appVars = appVars;
}


//...

}

最佳答案

 services.Configure<AppVars>(config1.GetSection("AppVars"));

寄存器IOptions<AppVars>而构造函数期望的只是 AppVars

相应地更新目标构造函数,以便它需要正确的类型

public class FileWriterService : IHostedService, IDisposable {
private const string Path = @"d:\TestApplication.txt";

private Timer _timer;
private AppVars _appVars;
public FileWriterService(IOptions<AppVars> appVars) {
_appVars = appVars.Value;
}

//...

}

或者

保留构造函数不变,并重构启动以注册所需的类型

var builder = new HostBuilder()
.ConfigureServices((hostContext, services) => {
services.AddHostedService<FileWriterService>();
AppVars appVars = hostContext.Configuration.GetSection("AppVars").Get<AppVars>();
services.AddSingleton(appVars);

});

关于c# - 将 appsettings 配置 DI 添加到 HostBuilder 控制台应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59274418/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com