使用自定义工厂使用Automapper创建目标类型

时间:2013-02-23 15:36:58

标签: c# automapper

我有CustomerDtoCustomerDomainModel。我希望Automapper在构造DataBindingFactory对象时使用CustomerDomainModel mentioned here。我查看了ConstructUsing课程中的AfterMapMapper函数,但我找不到按照我想要的方式完成任务的方法。我该怎么做?

1 个答案:

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