我有CustomerDto
和CustomerDomainModel
。我希望Automapper在构造DataBindingFactory
对象时使用CustomerDomainModel
mentioned here。我查看了ConstructUsing
课程中的AfterMap
和Mapper
函数,但我找不到按照我想要的方式完成任务的方法。我该怎么做?
答案 0 :(得分:3)
您应该可以使用ConstructUsing
。您可能必须显式地转换为这样的正确表达式:
class Program
{
private static void Main(string[] args)
{
Mapper.CreateMap<CustomerDto, CustomerDomainModel>()
.ForMember(d => d.Id, opt => opt.Ignore())
.ConstructUsing((Func<ResolutionContext, CustomerDomainModel>) (rc => DataBindingFactory.Create<CustomerDomainModel>()));
var dto = new CustomerDto {FirstName = "First", LastName = "Last"};
var domain = Mapper.Map<CustomerDto, CustomerDomainModel>(dto);
Console.WriteLine("First: " + domain.FirstName);
Console.WriteLine("Last: " + domain.LastName);
Console.ReadLine();
}
}
public class CustomerDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class CustomerDomainModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public static class DataBindingFactory
{
public static T Create<T>()
{
return Activator.CreateInstance<T>();
}
}