向非通用类注册通用接口

时间:2018-09-19 00:55:40

标签: c# dependency-injection unity-container

我的应用程序中具有通用接口:

public interface IBaseMapper<DTO, Entity> 
    where DTO : class, new()
    where Entity : class, new()
{
    List<DTO> EntityToDTO_Transform(List<Entity> requestEntity);
    Entity DTOEntity_Transform(DTO requestDTO);
}

哪个是由非泛型类实现的?

public class RequestMapper : IBaseMapper<RequestDTO,REQUEST>
{
    public REQUEST DTOEntity_Transform(RequestDTO requestDTO)
    {
        return Mapper.Map<RequestDTO, REQUEST>(requestDTO);
    }

    public List<RequestDTO> EntityToDTO_Transform(List<REQUEST> requestEntity)
    {
        return Mapper.Map<List<REQUEST>, List<RequestDTO>>(requestEntity);
    }
}

我将Unity用作依赖项注入的IoC容器。

如何解决依赖关系?

var container = new UnityContainer();

container.RegisterType(typeof(IBaseMapper<>), typeof(RequestMapper); // ???

config.DependencyResolver = new UnityDependencyResolver(container);

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

由于RequestMapper是非泛型的,因此在进行映射时需要指定其封闭的泛型抽象,如下所示:

container.RegisterType(
    typeof(IBaseMapper<RequestDTO,REQUEST>), 
    typeof(RequestMapper));