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>();
}
}