我想从数据库中注入一些电子邮件配置数据到名为AuthMessageSenderOptions
的配置类,此类具有以下属性:
public class AuthMessageSenderOptions
{
public int PortNumber { get; set; }
public string SmtpServer { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
为了在appsettings.json
到AuthMessageSenderOptions
类中注入配置详细信息,我在Startup.cs
中使用了这段代码:
services.Configure<AuthMessageSenderOptions>(Configuration.GetSection("SMTP"));
现在我的问题是:
如何从数据库而不是appsettings.json
读取此数据并将其注入我的AuthMessageSenderOptions
课程以供将来使用?
答案 0 :(得分:10)
您可以通过创建实现接口IConfigurationSource
的类并通过继承ConfigurationProvider
来实现自定义配置提供程序来创建自定义配置源。
首先,创建一个配置源来使用实体框架初始化数据源:
public class CustomMailConfigSource: IConfigurationSource
{
private readonly Action<DbContextOptionsBuilder> _dbOptions;
public CustomMailConfigSource(Action<DbContextOptionsBuilder> dbOptions)
{
_dbOptions = dbOptions;
}
public IConfigurationProvider Build(IConfigurationBuilder builder)
{
return new CustomMailConfigProvider(_dbOptions);
}
}
然后,实现自定义配置提供程序:
public class CustomMailConfigProvider: ConfigurationProvider
{
public CustomMailConfigProvider(Action<DbContextOptionsBuilder> dbOptions)
{
DbOptions = dbOptions;
}
Action<DbContextOptionsBuilder> DbOptions { get; }
public override void Load()
{
var builder = new DbContextOptionsBuilder<ConfigurationContext>();
DbOptions(builder);
using (var dbContext = new ConfigurationContext(builder.Options))
{
dbContext.Database.EnsureCreated();
//Modify this to suit your needs, here is an example assuming you have a table called AuthMessageSenderOption with the same fields as the class in your question
var authMessageSender = db.Context.AuthMessageSenders.FirstOrDefault();
// You should add some code here to check if the settings exist and provide defaults if necessary
Data = new Dictionary<string, string>
{
{ "PortNumber", authMessageSenderOption.PortNumber},
{ "SmtpServer", authMessageSenderOption.SmtpServer },
{ "UserName", authMessageSenderOption.UserName},
{ "Password", authMessageSenderOption.Password}
};
}
}
}
最后,您需要注册自定义配置提供程序。
创建IConfigurationBuilder
扩展程序:
public static class CustomProviderExtensions
{
public static IConfigurationBuilder AddCustomMailConfigProvider(
this IConfigurationBuilder builder, Action<DbContextOptionsBuilder> dbOptions)
{
return builder.Add(new CustomMailConfigSource(dbOptions));
}
}
使用您刚刚创建的扩展程序在Main()
方法中注册提供程序:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
// Add "appsettings.json" to bootstrap EF config.
.AddJsonFile("appsettings.json")
// Add the EF configuration provider, which will override any
// config made with the JSON provider.
.AddCustomMailConfigProvider(dbOptions =>
dbOptions .UseSqlServer(connectionStringConfig.GetConnectionString(
"DefaultConnection"))
)
.Build();
参考文献:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?tabs=basicconfiguration