像这样在我的应用程序中的Program.cs中注册配置
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("appsettings.secret.json", optional: true, reloadOnChange: true);
})
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{override configuration in NLog.config
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog(); // NLog: setup NLog for Dependency injection;
我有一个需要IConfigurationRoot实例的类
public class ConfiguredKeyDataProtectionProvider : IDataProtectionProvider
{
// Example configuration required for use of this class
// {
// "ConfiguredKeyDataProtectionProvider": {
// "Key": {
// "TestPurpose": "asda2516shah"
// }
// }
// }
private readonly IConfigurationRoot _configurationRoot;
public ConfiguredKeyDataProtectionProvider(IConfigurationRoot configurationRoot)
{
_configurationRoot = configurationRoot;
}
public IDataProtector CreateProtector(string purpose)
{
string encryptionKey = _configurationRoot.GetValue<string>("ConfiguredKeyDataProtectionProvider:Key:" + purpose);
return new ConfiguredKeyDataProtector(encryptionKey);
}
}
我正在尝试通过DI注册IConfiguredKeyDataProtectionProvider的实例。我期望已经注册了IConfiguration根实例(请注意,在StartUp.cs中重复读取配置文件-不确定是否需要这样做),IConfiguredKeyDataProtectionProvider将能够看到配置数据,但是似乎没有情况。
public class Startup
{
public Startup(IHostingEnvironment env)
{
var configurationRoot = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.secret.json", optional: true, reloadOnChange: true)
.Build();
Configuration = configurationRoot;
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfigurationRoot>(Configuration);
//...
services.AddTransient<IDataProtectionProvider, ConfiguredKeyDataProtectionProvider>();
我应该如何正确配置我的应用程序,以便可以通过依赖注入来注册构造函数上具有IConfigurationRoot的类?
答案 0 :(得分:1)
不确定为什么需要IConfigurationRoot
接口,但是由于在构造主机之前已经建立了IConfigurationRoot
的实例,因此您可以通过{{ 1}} :
此外,无需两次构建配置,只需调用 .ConfigureServices(services =>{services.AddSingleton<IConfigurationRoot>(configRoot);})
。
UseConfiguration(congfigRoot)