Wow, what a lot of comments, why don't people answer the question instead of telling someone they don't want to do what they obviously do. Anyway, hopefully this will keep both camps satisfied.
If you take a standard AppSettings class with a single public constructor that takes an IConfiguration that can be used to populate all the AppSettings properties, this keeps the ability for Dependency Injection.
If at the end of the constructor we set a static property 'Current' pointing to the current instance of AppSettings, this will allow us access to the settings from that point onwards via the static property without the need for further injection.
If we now create a static Default 'GetCurrentSettings' method to get the settings from a json file, this can be used as a default instantiation, so that if 'Current' is called and is set to null, we just go off and populate the settings from the file. Here's an example of what I mean...
public class AppSettings
{
private static AppSettings _appSettings;
public string AppConnection { get; set; }
public AppSettings(IConfiguration config)
{
this.AppConnection = config.GetValue<string>("AppConnection");
// Now set Current
_appSettings = this;
}
public static AppSettings Current
{
get
{
if(_appSettings == null)
{
_appSettings = GetCurrentSettings();
}
return _appSettings;
}
}
public static AppSettings GetCurrentSettings()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
IConfigurationRoot configuration = builder.Build();
var settings = new AppSettings(configuration.GetSection("AppSettings"));
return settings;
}
}
So from this you would be able to call anywhere in code AppSettings.Current.AppConnection
If it's been instantiated using DI the injected version would be retrieved otherwise the default version would be taken from an appsettings.json file. I doubt it satisfies everyone and I'm not sure I've explained it very well, but hopefully it makes sense.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…