在AutoMapper中为Map函数设置模拟期望的最佳方式是什么?使用Moq模拟AutoMapper Mapper.Map调用
我提取IMapper接口,以便我可以设置期望的接口。我的映射器有依赖关系,所以我必须将它们传递给映射器。
当我创建2个我的映射器类,2个不同的依赖实现时会发生什么?我假定两个映射器都将使用相同的依赖实例,因为AutoMapper映射是静态的。或者AutoMapper甚至可能会抛出一个异常,因为我试图用相同的对象设置2个不同的地图。
最好的解决办法是什么?
public interface IMapper {
TTarget Map<TSource, TTarget>(TSource source);
void ValidateMappingConfiguration();
}
public class MyMapper : IMapper {
private readonly IMyService service;
public MyMapper(IMyService service) {
this.service = service
Mapper.CreateMap<MyModelClass, MyDTO>()
.ForMember(d => d.RelatedData, o => o.MapFrom(s =>
service.getData(s.id).RelatedData))
}
public void ValidateMappingConfiguration() {
Mapper.AssertConfigurationIsValid();
}
public TTarget Map<TSource, TTarget>(TSource source) {
return Mapper.Map<TSource, TTarget>(source);
}
}