Too late, but after reading all helpful answers and comments, I ended up using Microsoft.Extensions.Configuration.Binder extension package and play a little around to get rid of hardcoded configuration keys.
My solution:
IConfigSection.cs
public interface IConfigSection
{
}
ConfigurationExtensions.cs
public static class ConfigurationExtensions
{
public static TConfigSection GetConfigSection<TConfigSection>(this IConfiguration configuration) where TConfigSection : IConfigSection, new()
{
var instance = new TConfigSection();
var typeName = typeof(TConfigSection).Name;
configuration.GetSection(typeName).Bind(instance);
return instance;
}
}
appsettings.json
{
"AppConfigSection": {
"IsLocal": true
},
"ConnectionStringsConfigSection": {
"ServerConnectionString":"Server=.;Database=MyDb;Trusted_Connection=True;",
"LocalConnectionString":"Data Source=MyDb.db",
},
}
To access a strongly typed config, you just need to create a class for that, which implements IConfigSection interface(Note: class names and field names should exactly match section in appsettings.json)
AppConfigSection.cs
public class AppConfigSection: IConfigSection
{
public bool IsLocal { get; set; }
}
ConnectionStringsConfigSection.cs
public class ConnectionStringsConfigSection : IConfigSection
{
public string ServerConnectionString { get; set; }
public string LocalConnectionString { get; set; }
public ConnectionStringsConfigSection()
{
// set default values to avoid null reference if
// section is not present in appsettings.json
ServerConnectionString = string.Empty;
LocalConnectionString = string.Empty;
}
}
And finally, a usage example:
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// some stuff
var app = Configuration.GetConfigSection<AppConfigSection>();
var connectionStrings = Configuration.GetConfigSection<ConnectionStringsConfigSection>();
services.AddDbContext<AppDbContext>(options =>
{
if (app.IsLocal)
{
options.UseSqlite(connectionStrings.LocalConnectionString);
}
else
{
options.UseSqlServer(connectionStrings.ServerConnectionString);
}
});
// other stuff
}
}
To make it neat, you can move above code into an extension method.
That's it, no hardcoded configuration keys.