根据其他类型从集合中检索泛型类

时间:2018-06-13 01:07:57

标签: c# .net generics .net-core polymorphism

我无法在单独的服务中实现封装某些CRUD逻辑和dto-entity映射的解决方案,并且真的可以使用一些帮助。

因此,假设我们有下一个接口,为数据存储提供访问端点,我们每个实体都有一个单独的客户端

public interface IClient<T> where T : class
{
    T Get();
    void Set(T entity);
}

然后我们将ClientService作为聚合器,为所有现有客户端提供单一访问点

public class A { };
public class B { };

public class ClientService
{
    private IDictionary<Type, object> _clientDict;

    public ClientService(IClient<A> clientA, IClient<B> clientB)
    {
        _clientDict = new Dictionary<Type, object>
        {
            { typeof(A), clientA },
            { typeof(B), clientB }
        };
    }

    public T Get<T>() where T : class
    {
        var client = this.GetClient<T>();
        return client.Get();
    }

    public void Set<T>(T entity) where T : class
    {
        var client = this.GetClient<T>();
        client.Set(entity);
    }

    private IClient<T> GetClient<T>() where T : class
    {
        if (_clientDict.TryGetValue(typeof(T), out object client))
        {
            return (IClient<T>)client;
        }

        throw new ArgumentException();
    }
}

到目前为止一切都很好。

现在问题。我需要将其转换为使用DTO对象与IClient<T>一起使用,同时仍然接受ClientService的非DTO模型。 伪代码:

public class A { };
public class A_DTO { };
public class B { };
public class B_DTO { };

public class ClientService
{
    private IDictionary<Type, object> _clientDict;

    public ClientService(IClient<A_DTO> clientA, IClient<B_DTO> clientB)
    {
        _clientDict = new Dictionary<Type, object>
        {
            { typeof(A), clientA },
            { typeof(B), clientB }
        };
    }

    public void Set<T>(T entity) where T : class
    {
        var dtoType = GetDTOType(T);
        var dtoEntity = _autoMapper.Map(entity, typeof(T), GetDTOType(T));

        var client = this.GetClient<T, dtoType>();
        client.Set(dtoEntity);
    }

    private IClient<DTO> GetClient<T, DTO>() where T : class
                                            where DTO: class
    {
        if (_clientDict.TryGetValue(typeof(T), out object client))
        {
            return (IClient<DTO>)client;
        }

        throw new ArgumentException();
    }
}

我确实理解,由于泛型在编译期间被解析,我们无法使它们依赖于变量,但是可能有任何其他方式我们可以让客户端使用,即是否存在我们如何实现IClient<T2> GetClient<T1, T2> T1 A T2A_DTO Get<A>()的任何方式? 请注意,最终用户无权访问DTO对象,因此无法将其作为通用类型提供,并且所有内容都需要在内部进行。

是否存在任何通用实现,或者我只是在浪费时间,应该为每个客户端实现创建特定方法(例如Get<B>,{{1}}等)?

1 个答案:

答案 0 :(得分:0)

您实际上不需要在您的客户服务类中包含您的DTO。一旦你的模型开始增长,这肯定会变得混乱。你可以做的是使用AutoMapper之类的工具将结果从服务类转换为你的dtos。这很简单。你可以有这样的事情:

{{1}}

有关详细信息,请参阅链接。