2

我需要实现一个可插入系统,其中 Automapper 配置文件可以由许多 DLL 提供。

要映射的对象有一个人员列表:

public class CompanySrc
{
    public List<PersonSrc> Persons {get;set;}
}

public class CompanyDest
{
    public List<PersonDest> Persons {get;set;}
}

PersonSrc 和 PersonDest 是可以在每个 DLL 中扩展的抽象类:

DLL1:

public class EmployeeSrc : PersonSrc
{
    ...
}


public class EmployeeDest : PersonDest
{
    ...
}

DLL2:

public class ManagerSrc : PersonSrc
{
    ...
}


public class ManagerDest : PersonDest
{
    ...
}

这个想法是实现类似的东西:

public class DLL1Profile : Profile
{
    public DLL1Profile()
    {
        CreateMap<PersonSrc, PersonDest>()
               .Include<EmployeeSrc, EmployeeDest>();
        CreateMap<EmployeeSrc, EmployeeDest>();
    }
}


public class DLL2Profile : Profile
{
    public DLL2Profile()
    {
        CreateMap<PersonSrc, PersonDest>()
                .Include<ManagerSrc, ManagerDest>();
        CreateMap<ManagerSrc, ManagerDest>();
    }
}

映射是通过以下方式完成的

var mc = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<CompanySrc, CompanyDest>()
                cfg.AddProfile(new DLL1Profile());
                cfg.AddProfile(new DLL2Profile ());
            });

            IMapper sut = mc.CreateMapper();
            var result = sut.Map<CompanyDest>(companySrc);

但这种方法行不通。当“人员”列表包含员工和经理时,我尝试映射整个列表时出现异常。有什么建议吗?

4

1 回答 1

1

您看到此问题是因为您有多次调用CreateMap<PersonSrc, PersonDest>()- 只能存在一个映射。

当你在不同的 DLL 中扩展你的基类时,不要使用.Include.IncludeBase而是使用。Include 要求包含您的基类的配置文件能够引用派生类,这很可能不是您想要发生的。

您应该在某个常见的地方定义基本映射,大概是定义 Person 的地方:

CreateMap<PersonSrc, PersonDest>();

在您的 DLL1 配置文件等中,请IncludeBase改用:

CreateMap<ManagerSrc, ManagerDest>()
    .IncludeBase<PersonSrc, PersonDest>();
于 2017-07-10T10:02:37.797 回答