在ASP.NET Core DI中支持基于属性的设置引用解析的最简单方法是什么?我想做这样的事情来读取配置值:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
public WeatherForecastController(
[Setting("Logging:LogLevel:Microsoft")] string logLevel)
{
…
当appsettings.json
看起来像:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
…
有什么想法如何处理吗?我希望它也能为服务工作。
从技术上讲,可以使用MS.DI来实现这一点,但是要做到这一点非常困难,而且正如Dmitry所述,成熟的DI容器(例如Autofac或Simple Injector)将给您带来更多的运气。
如果您真的想继续使用MS.DI,请参考以下代码:
var settingDescriptors = (
from descriptor in services
let type = descriptor.ImplementationType
where type != null && !type.IsGenericTypeDefinition
where type.GetConstructors().Single().GetParameters()
.Any(p => p.GetCustomAttribute<SettingAttribute>() != null)
select descriptor)
.ToArray();
foreach (var descriptor in settingDescriptors)
{
services.Remove(descriptor);
object[] settings = // TODO: Determine settings from parameters here
services.Add(new ServiceDescriptor(
descriptor.ServiceType,
c => ActivatorUtilities.CreateInstance(
c,
descriptor.ImplementationType,
settings),
descriptor.Lifetime));
}
此代码的作用是遍历服务集合,并替换具有构造函数参数(以标记为)的实现的所有注册SettingAttribute
。该注册将替换为使用工厂委托的注册,该工厂委托要求DI容器创建一个实例,同时为其提供一个或多个对象(设置)。换句话说,它在手动提供对象的同时启用了自动装配。
这意味着在某种程度上,MS.DI是可以实现的,但是...您应考虑一些严重的限制:
ActivatorUtilities.CreateInstance
百叶窗的DI系统。如果MS.DI包含防止循环依赖的检查,则在循环依赖的情况下,使用ActivatorUtilities.CreateInstance
会导致难以调试堆栈溢出异常。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句