首页 > 解决方案 > 获取开放的泛型类型列表 .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
}

现在我确实得到了一份客户名单,但是,演员阵容失败了。请帮忙

标签: c#asp.net-core.net-core

解决方案


推荐阅读