我正在替换静态AutoMapper API:
所以,在我有Profile
之前:
public class DigitalResourceProfile : AutoMapper.Profile
{
protected override void Configure()
{
AutoMapper.Mapper.CreateMap<DTO, Domain>();
AutoMapper.Mapper.CreateMap<Domain, DTO>()
.ForMember(dst => dst.Attachs, opts => opts.MapFrom(src => AutoMapper.Mapper.Map<List<AttachDomain>, List<AttachDTO>>(src.Attachs)))
.ForMember(dst => dst.Timestamp, opts => opts.MapFrom(s => s.Timestamp.ToUniversalTime()));
AutoMapper.Mapper.CreateMap<AttachDTO, AttachDomain>();
AutoMapper.Mapper.CreateMap<AttachDomain, AttachDTO>()
.ForMember(dst => dst.Timestamp, opts => opts.MapFrom(s => s.Timestamp.ToUniversalTime()));
}
}
从现在开始,此个人资料类就像:
public class DigitalResourceProfile : AutoMapper.Profile
{
protected override void Configure()
{
this.CreateMap<DTO, Domain>();
this.CreateMap<Domain, DTO>()
>>>>>>>>>>>>>>>>>.ForMember(dst => dst.Attachs, opts => opts.MapFrom(src => AutoMapper.Mapper.Map<List<AttachDomain>, List<AttachDTO>>(src.Attachs)))
.ForMember(dst => dst.Timestamp, opts => opts.MapFrom(s => s.Timestamp.ToUniversalTime()));
this.CreateMap<AttachDTO, AttachDomain>();
this.CreateMap<AttachDomain, AttachDTO>()
.ForMember(dst => dst.Timestamp, opts => opts.MapFrom(s => s.Timestamp.ToUniversalTime()));
}
}
但是,我不知道如何替换.ForMember(dst => dst.Attachs, opts => opts.MapFrom(src => AutoMapper.Mapper.Map<List<AttachDomain>, List<AttachDTO>>(src.Attachs)))
。
有什么想法吗?
答案 0 :(得分:1)
您可以通过Profile contructor传递映射引擎,而不是使用静态API。
您将在下面找到使用Unity的单元测试。
[TestClass]
public class UnitTest1
{
public class TestA
{
public TestC valueA { get; set; }
}
public class TestB
{
public TestD valueB { get; set; }
}
public class TestC
{
public string value { get; set; }
}
public class TestD
{
public string value { get; set; }
}
private readonly IUnityContainer appContainer = new UnityContainer();
public sealed class MappingConfiguration : Profile
{
private readonly IMappingEngine mappingEngine;
// Inject mapping engine through constructor
public MappingConfiguration(IMappingEngine mappingEngine)
: base()
{
this.mappingEngine = mappingEngine;
}
protected override void Configure()
{
CreateMap<TestA, TestB>()
.ForMember(dest => dest.valueB, o => o.ResolveUsing(src =>
this.mappingEngine.Mapper.Map<TestD>(src.valueA)));
CreateMap<TestC, TestD>();
}
}
[TestMethod]
public void MappingTest()
{
// AutoMapper configuration
var config = new MapperConfiguration(cfg =>
{
cfg.ConstructServicesUsing(type => appContainer.Resolve(type));
});
var mapper = config.CreateMapper();
appContainer.RegisterInstance<IConfiguration>(config);
appContainer.RegisterType<IMappingEngine, MappingEngine>(new InjectionConstructor(config, mapper));
appContainer.Resolve<IConfiguration>().AddProfile(new MappingConfiguration(appContainer.Resolve<IMappingEngine>()));
// Check config
mapper.ConfigurationProvider.AssertConfigurationIsValid();
var testIn = new TestA { valueA = new TestC { value = "This is a test" } };
var result = mapper.Map<TestB>(testIn);
}
}