我试图在其中使用HostBuilder的.net核心控制台应用程序中包含一个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"));
});
...
}
在下面,我试图在一个类中注入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;
}
答案 0 :(得分:1)
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 config1 = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true)
.Build();
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) => {
services.AddHostedService<FileWriterService>();
AppVars appVars = config1.GetSection("AppVars").Get<AppVars>();
services.AddSingleton(appVars);
});