gpt4 book ai didi

c# - AutoMapper 5.2如何配置

转载 作者:可可西里 更新时间:2023-11-01 08:16:08 29 4
gpt4 key购买 nike

为全局使用配置 AutoMapper 的正确方法是什么。

我想设置一次,然后在整个应用程序中使用。

我有一种强烈的感觉,这是错误的。事实上,我知道这是错误的,因为这会调用一个新实例。我想要一个全局配置,然后你怎么调用它。找不到好的例子!

这就是我得到的:但这不是我想要的

public static class AutoMapperConfig
{
public static IMapper GetMapper()
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<R_Logo, LogoDto>();
//lots more maps...?
});

IMapper mapper = config.CreateMapper();
return mapper;
}
}

然后是用法:

  var imapper = AutoMapperConfig.GetMapper();
var dest = imapper.Map<R_Logo, LogoDto>(logo);

更新基于:pinkfloydx33

调用一次,然后配置完成。

public static class AutoMapperConfig
{
public static void RegisterMappings()
{
AutoMapper.Mapper.Initialize(cfg => {
cfg.CreateMap<R_Logo, LogoDto>();
/* etc */
});
}
}

最佳答案

这是在 asp.net core mvc 中配置自动映射器的步骤。

1. 创建从 Profile

扩展的映射配置文件类
 public class ClientMappingProfile : Profile
{
public ClientMappingProfile ()
{
CreateMap<R_Logo, LogoDto>().ReverseMap();
}
}

2.创建 AutoMapper 配置类并在此处添加您的映射配置文件类。

public class AutoMapperConfiguration
{
public MapperConfiguration Configure()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<ClientMappingProfile>();
});
return config;
}
}

3.我们如何使用它。

       var config = new AutoMapperConfiguration().Configure();
var iMapper = config.CreateMapper();

var dest = iMapper.Map<R_Logo, LogoDto>(logo);

关于c# - AutoMapper 5.2如何配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42508231/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com