c# - 获取开放的泛型类型列表 .Net Core
问题描述
如何解决实现的多个注册。我想获取实现者列表:
登记:
services.AddScoped(typeof(IClient<>), typeof(Client1));
services.AddScoped(typeof(IClient<>), typeof(Client2));
我正在尝试这样做:
public class ClientFactory : IClientFactory
{
private readonly IServiceProvider _serviceProvider;
public ClientFactory(
IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IClient<ListingBase> GetClient(string clientName)
{
var clients = _serviceProvider.GetServices<IClient<ListingBase>>(); // listing base is abstracct class
// match by name - filter by name
// do stuff here
return (IClient<ListingBase>)clients.FirstOrDefault();
}
}
得到:
执行功能时出现异常:Importer。System.Linq.Expressions:“Client1”类型的表达式不能用于初始化“IClient`1[..Abstract.ListingBase] 类型的数组
当我只注册一个实例并执行时,它确实有效.GetService<IClient<ListingBase>>()
但是我想获得所有实现者的列表。
编辑:为清楚起见添加更多代码:
public interface IClient<TModel> : IClient where TModel : ListingBase
{
public Task<TModel> MapToObject(Stream file);
}
public interface IClient { }
public abstract class ClientBase<TModel> : IClient<TModel> where TModel : ListingBase
{
// .. other common stuff
public abstract Task<TModel> MapToObject(Stream file);
}
实现:
public class Client1 : ClientBase<Model1> // Model1 inherits from ListingBase
{
{
public override Task<Model1> MapToObject(Stream file) // Model1 inherits from ListingBase
{
// do mapping from Json / Stream to object
return Task.FromResult(new Model1());
}
}
// Another client
public class Client2 : ClientBase<Model2> // Model2 inherits from ListingBase
{
{
public override Task<Model2> MapToObject(Stream file) // Model2 inherits from ListingBase
{
// do mapping from Json / Stream to object
return Task.FromResult(new Model2());
}
}
将其更改为:
services.AddScoped(typeof(IClient), typeof(SaborClient));
services.AddScoped(typeof(IClient), typeof(FlexClient));
...
public IClient<ListingBase> GetClient(string clientName)
{
var clients = _serviceProvider.GetServices(typeof(IClient));
// match by name
var t = clients.FirstOrDefault();
return (IClient<ListingBase>) t; // failing here
}
现在我确实得到了一份客户名单,但是,演员阵容失败了。请帮忙
解决方案
推荐阅读
- oracle11g - 未使用 Oracle 基线
- mapbox - wkhtmltopdf (wicked_pdf) + 绘制地图(最好是Mapbox)
- android - Android Frida钩子构造函数?
- php - 有什么方法可以将内容添加到基本模板而不在每个操作中传递变量?
- javascript - 加载新的html页面时,JS变量会被破坏吗?
- php - 如何传递多个参数(request + 2 another params)
- node.js - Winston/Node.js 如何仅为特定路线添加传输?
- c# - 如何在不调用操作的情况下检查速率是否受限
- scala - 从protobuf反序列化json对象返回空
- python-3.x - 如何根据我使用 @pytest.mark.skipif 设置的 self.skip_flag 跳过测试