Reputation: 75
I am using the following (class/interface names changed) to bind a configuration file section to a model class and add it as a service. I then inject it into the class I want to use it in. Everything works great as long as that section is there in the config file. Trouble is this section may not get updated on all the instances right away so we that section to be optional.
So when the section isn't there, the startup runs fine, but my class with the dependency crashes hard. How could I set this up that it works even without that config section. Maybe send in a null initialized object? Or make it optional somehow? I'm sorry if I'm missing something obvious, brain a bit fried trying to get this out quickly.
services.AddSingleton<ISettingsPoco>((serviceProvider) =>
{
return config.GetSection("SettingsSection").Get<SettingsPOCO>();
});
Upvotes: 0
Views: 531
Reputation: 1619
var sectionExists = Configuration.GetChildren().Any(item => item.Key == "SettingsSection"));
You can do a call on the keys you are looking for to see if they exist first. IF so then you can run the code to get the section. Of course if it does not exist do not bind it. If it does then run the code as you have it above.
Upvotes: 1