1
我有CustomerDto
和CustomerDomainModel
。我希望Automapper在构建CustomerDomainModel
对象时使用DataBindingFactory
mentioned here。我已经看过ConstructUsing
和AfterMap
功能Mapper
班,但我找不到我想要做的事情。我该怎么做呢?使用自定义工厂使用Automapper创建目标类型
我有CustomerDto
和CustomerDomainModel
。我希望Automapper在构建CustomerDomainModel
对象时使用DataBindingFactory
mentioned here。我已经看过ConstructUsing
和AfterMap
功能Mapper
班,但我找不到我想要做的事情。我该怎么做呢?使用自定义工厂使用Automapper创建目标类型
你应该可以使用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>();
}
}