如何在类库项目中配置Auto mapper?

bni*_*nil 30 c# automapper automapper-2 automapper-3

我是第一次使用自动映射.

我正在研究c#应用程序,我想使用自动映射器.

(我只是想知道如何使用它,所以我没有asp.net应用程序既没有MVC应用程序.)

我有三个类库项目.

在此输入图像描述

我想在服务项目中编写转移过程.

所以我想知道如何以及在哪里配置自动映射器?

sev*_*rin 28

您可以将配置放在任何位置:

public class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(x =>
            {
                x.AddProfile<MyMappings>();              
            });
    }
}

 public class MyMappings : Profile
{
    public override string ProfileName
    {
        get { return "MyMappings"; }
    }

    protected override void Configure()
    {
    ......
    }
Run Code Online (Sandbox Code Playgroud)

但是必须在某个时候使用库来调用它:

void Application_Start()
    {               
        AutoMapperConfiguration.Configure();
    }
Run Code Online (Sandbox Code Playgroud)


Mar*_*rko 23

因此,基于Bruno在这里的回答和John Skeet关于单身人士的帖子,我提出了以下解决方案,让它只运行一次并在类库中完全隔离,而不像接受的答案依赖于库的使用者来配置映射中的映射.父项目:

public static class Mapping
{
    private static readonly Lazy<IMapper> Lazy = new Lazy<IMapper>(() =>
    {
        var config = new MapperConfiguration(cfg => {
            // This line ensures that internal properties are also mapped over.
            cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
            cfg.AddProfile<MappingProfile>();
        });
        var mapper = config.CreateMapper();
        return mapper;
    });

    public static IMapper Mapper => Lazy.Value;
}

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Source, Destination>();
        // Additional mappings here...
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您需要将一个对象映射到另一个对象的代码中,您可以执行以下操作:

var destination = Mapping.Mapper.Map<Destination>(yourSourceInstance);
Run Code Online (Sandbox Code Playgroud)

注意:此代码基于AutoMapper 6.2,可能需要对旧版本的AutoMapper进行一些调整.

  • 谢啦。这是最好的答案,因为它除了自身以外不依赖其他任何内容。 (3认同)

Bru*_*ell 5

库外的任何人都不必配置AutoMapper

我建议您通过使用基于实例的方法IMapper。这样,库外的任何人都不必调用任何配置方法。您可以定义一个,MapperConfiguration然后从该类库中的所有位置创建映射器。

var config = new MapperConfiguration(cfg => {
    cfg.AddProfile<AppProfile>();
    cfg.CreateMap<Source, Dest>();
});

IMapper mapper = config.CreateMapper();
// or
IMapper mapper = new Mapper(config);
var dest = mapper.Map<Source, Dest>(new Source());
Run Code Online (Sandbox Code Playgroud)

  • 我们可以将这段代码放在类库中的什么位置,以便它自动被调用(仅一次)? (2认同)