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

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

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

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

我有三个类库项目。

在此处输入图像描述

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

所以我想知道如何以及在哪里配置Auto Mapper?

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

public class AutoMapperConfiguration { public static void Configure() { Mapper.Initialize(x => { x.AddProfile(); }); } } public class MyMappings : Profile { public override string ProfileName { get { return "MyMappings"; } } protected override void Configure() { ...... } 

但是必须由应用程序在某些时候使用库来调用它:

 void Application_Start() { AutoMapperConfiguration.Configure(); } 

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

 public static class Mapping { private static readonly Lazy Lazy = new Lazy(() => { 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(); }); var mapper = config.CreateMapper(); return mapper; }); public static IMapper Mapper => Lazy.Value; } public class MappingProfile : Profile { public MappingProfile() { CreateMap(); // Additional mappings here... } } 

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

 var destination = Mapping.Mapper.Map(yourSourceInstance); 

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

您图书馆外的任何人都不得配置AutoMapper

我建议您使用IMapper使用基于实例的方法 。 这样,你的库外没有人必须调用任何配置方法。 您可以定义MapperConfiguration并从MapperConfiguration创建映射器。

 var config = new MapperConfiguration(cfg => { cfg.AddProfile(); cfg.CreateMap(); }); IMapper mapper = config.CreateMapper(); // or IMapper mapper = new Mapper(config); var dest = mapper.Map(new Source()); 
Interesting Posts