我有一个接口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解决第二个单例。
答案 0 :(得分:1)
注册类,并在注册接口时使用委托工厂获取注册的类。
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;
//...
}