为时已晚,但在阅读了所有有用的答案和 cmets 之后,我最终使用了 Microsoft.Extensions.Configuration.Binder 扩展包并尝试摆脱硬编码的配置键。
我的解决方案:
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",
},
}
要访问强类型配置,您只需要为此创建一个类,该类实现 IConfigSection 接口(注意:类名和字段名应完全匹配部分在 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;
}
}
最后是一个用法示例:
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
}
}
为了简洁,你可以将上面的代码移到扩展方法中。
就是这样,没有硬编码的配置键。