在 AutoMapper 中为 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);
}
}