【发布时间】:2020-01-27 23:25:40
【问题描述】:
我有这样的选择:
public class ApplicationSettings
{
public string Title { get; set; }
public string PluginFolders { get; set; }
}
还有这样的服务:
public interface IWildcardResolver
{
string Resolve(string value);
}
public class WildcardResolver : IWildcardResolver
{
private readonly IHostingEnvironment _hostingEnvironment;
public WildcardResolver(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
AddWildcard("%contentRootPath%", _hostingEnvironment.ContentRootPath);
AddWildcard("%webRootPath%", _hostingEnvironment.WebRootPath);
AddWildcard("%environment%", _hostingEnvironment.EnvironmentName);
}
private readonly Dictionary<string, string> _hardWiredValues = new Dictionary<string, string>();
/// <inheritdoc />
public string Resolve(string value)
{
var sb = new StringBuilder(value);
foreach (var pair in _hardWiredValues)
{
sb.Replace(pair.Key, pair.Value);
}
return sb.ToString();
}
public void AddWildcard(string name, string value)
{
if (_hardWiredValues.ContainsKey(name))
throw new Exception($"A value for the wildcard {name} already exists.");
_hardWiredValues.Add(name, value);
}
}
如何确保在通过 DI 访问这些设置之前使用 IOptions<AppSettings> PluginFolders 进行翻译(因为它包含通配符)?我已经尝试过IConfigureOptions<AppSettings> 和IPostConfigureOptions<AppSettings>,但它们似乎都发生在一个为时已晚的阶段。就像我缺少 IPreConfigureOptions 或其他东西一样。
public class PluginManager
{
private readonly IOptions<ApplicationSettings> _settings;
public PluginManager(IOptions<ApplicationSettings> settings)
{
_settings = settings;
// how do i get an instance here which makes sure that the ApplicationSettings.PluginPaths is already manipulated without doing it manually?
}
}
这样做是可行的,但感觉就像我在与框架作斗争,因为我不能像其他任何地方一样使用IOptions<AppSettings>:
【问题讨论】:
-
或者甚至是我认为更符合您想要做的事情docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/…
标签: c# asp.net-core options