如何在构造函数中使用AutoMapper映射到"this"

g.p*_*dou 6 c# automapper automapper-2 automapper-3

我有一个源类型,它具有属性和目标类型,具有完全相同的属性.

为AutoMapper配置一个简单的映射后,如:

Mapper.CreateMap<MySourceType, MyDestinationType>();
Run Code Online (Sandbox Code Playgroud)

我想有一个MyDestinationType的构造函数,它有一个MySourceType参数,然后自动初始化创建类型的属性,源代码如下:

public MyDestinationType(MySourceType source)
{
    // Now here I am do not know what to write.
}
Run Code Online (Sandbox Code Playgroud)

我找到的唯一解决方法是为其创建一个静态工厂方法

public static MyDestinationType Create(MySourceType source)
{
     return Mapper.Map<MyDestinationType>(source);
}
Run Code Online (Sandbox Code Playgroud)

有没有办法不让这种静态的丑陋?

Ale*_*lex 9

虽然我个人觉得它很丑,但你能做的是以下几点:

public MyDestinationType(MySourceType source)
{
    Mapper.Map<MySourceType, MyDestinationType>(source, this);
}
Run Code Online (Sandbox Code Playgroud)