这个问题对我来说似乎很有趣,因为我最近一直在处理类似的事情,并且我有三种不同的方法(非常欢迎 cmets,优点和缺点):
1.a. - 第一个也是hacky...如果您在其中添加一个扩展方法(我们称之为UtilsProvider)然后您在
中获得调用该estension方法的配置
public static class UtilsProvider
{
private static string _configItemOne;
public static IServiceProvider SetUtilsProviderConfiguration(this IServiceProvider serviceProvider, IConfigurationRoot configuration)
{
// just as an example:
_configItemOne= configuration.GetValue<string>("CONFIGITEMONE");
return serviceProvider;
}
// AND ALL YOUR UTILS THAT WOULD USE THAT CONFIG COULD USE IT
}
并且,该扩展方法将从您的 Startup 类 Configure 方法中调用:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
{
#region AddUtilsConfig
serviceProvider.SetUtilsProviderConfiguration(Configuration);
#endregion
...
1.b。 - 除了传递整个 IConfigurationRoot 实例,我们还可以将许多东西(例如具体参数或客户端)传递给保存环境配置值的服务,并在您第一次需要该配置属性时从静态类调用该服务。
2.- 此处描述了另一种也应该有效的方法(下面的链接),但包含类似的内容,它是将 HostingEnvironment 传递给启动类中相同配置方法中的静态类 (http://www.blakepell.com/asp-net-core-dependency-injection-and-custom-classes)
public static class UtilsProvider
{
public static IHostingEnvironment HostingEnvironment { get; set; }
...
}
在启动时...
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Have to be careful with static properties, they persist throughout the life time
// of the application.
UtilsProvider.HostingEnvironment = env;
}