我需要实现一个可插入系统,其中 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);
但这种方法行不通。当“人员”列表包含员工和经理时,我尝试映射整个列表时出现异常。有什么建议吗?