I created a .net core worker service, had IConfiguration injected into it so I can read a property from appsettings.json but everytime I run the file the property comes up as null. However if I force the IConfiguration to add a json file via the ConfigurationBuilder it works. How can I use the default settings to allow .net core worker service to read from appsettings?
public class ImageFileWatcher : IHostedService, IDisposable
{
private readonly ILogger _logger;
private readonly IConfiguration _configuration;
FileSystemWatcher _watcher;
public ImageFileWatcher(ILogger<ImageFileWatcher> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
// IConfigurationBuilder builder = new ConfigurationBuilder()
// .AddJsonFile("appsettings.json")
// .AddEnvironmentVariables();
// this._configuration = builder.Build();
}
public Task StartAsync(CancellationToken cancellationToken)
{
var watcherConfig = _configuration["WatcherConfig:filePath"];//this is where it comes up as null.
_logger.LogInformation($"Image File watcher started on path{watcherConfig}");
_watcher = new FileSystemWatcher(watcherConfig);
_watcher.Created += OnNewImage;
_watcher.EnableRaisingEvents = true;
return Task.CompletedTask;
}
Here is the appsettings.json file
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"WatcherConfig":{
"filePath":"/Users/###/Documents/Development/ImageDrop"
}
}
Here is the Program.cs file
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostContext, configBuilder) =>
{
configBuilder
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile("appsettings.Production.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables(prefix: "ImageService_")
.Build();
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<ImageFileWatcher>();
});
}
Here is the second attempt at the Program class:
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 builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile("appsettings.Production.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables(prefix: "ImageService_")
.Build();
hostContext.Configuration = builder;
services.AddHostedService<ImageFileWatcher>();
});
}