c# - .NET Core 依赖注入 - 解析接口的实现和 IEnumerable
问题描述
我有IMyType
几个实现的接口SomeMyType
,OtherMyType
.
我想同时使用具体类型,以及实现IMyType
接口的所有类型的 IEnumerable。
这些可能是服务中的声明。
private readonly IEnumerable<IMyType> instances;
private readonly SomeMyType someType;
private readonly OtherMyType otherType;
完成这项工作的一种方法是使用以下扩展:
public static IServiceCollection AddMyType<T>(this IServiceCollection serviceCollection)
where T : class, IMyType =>
serviceCollection
.AddSingleton(typeof(IMyType), typeof(T))
.AddSingleton(typeof(T));
这为具体类型和接口添加了一个单例。
这是配置依赖项的好方法吗?
还有其他改进解决方案的方法吗?我在想这是否会创建两个 T 实例,或者框架是否试图用第一个 T 解析第二个单例。
解决方案
注册类,注册接口时,使用委托工厂获取注册类。
public static IServiceCollection AddMyType<T>(this IServiceCollection serviceCollection)
where T : class, IMyType =>
serviceCollection
.AddSingleton<T>();
.AddSingleton<IMyType>(sp => sp.GetService<T>());
哪个会像
services.AddMyType<SomeMyType>();
services.AddMyType<OtherMyType>();
为了在这种情况下解决您的服务,为了获得所有已注册的IMyType
,注入IEnumerable<IMyType>
private readonly IEnumerable<IMyType> instances;
public MyClass(IEnumerable<IMyType> instances) {
this.instances = instances;
//...
}
已经注册的具体类型也可以根据需要显式注入
private readonly SomeMyType someType;
public MyClass(SomeMyType someType) {
this.someType = someType;
//...
}
推荐阅读
- c# - 在while循环中返回
- python - 如何在两个字符串中找到匹配的单词?
- event-log - 如何在很长一段时间内仅自动存储安全日志中的登录事件信息?
- mysql - Laravel - 验证用户输入的唯一值
- android - 微调器不显示项目
- python - Windows python setup.py install does not distribute module python files
- sql - T-SQL drop multiple tables error subquery returned more than 1 value
- python - 如何遍历长度在 python 中发生变化的字典?
- javascript - 是否可以使用 JS 导航到具有授权标头的不同域?
- jquery - External + Inline Styles vs. External Only