c# - 将 Automapper 与 ASP.NET Core 结合使用

标签 c# asp.net-core automapper

我正在尝试在 n 层应用程序上使用具有依赖注入(inject)配置的 Automapper。

 public class ApplicationMapping : Profile
{
    public ApplicationMapping()
    {
        RegisterMappings();
        Mapper.AssertConfigurationIsValid();
    }  

    private void RegisterMappings()
    {
      CreateMap<IEnumerable<App>, ListAppsDto>()
            .ForMember(dest => dest.Apps,
                       opt => opt.MapFrom(src =>
                            Mapper.Map<IEnumerable<App>, List<App>>(src.ToList())
                           )
                      );
    }
}

这个类在我的 Application 里面dll,我放置服务和 DTO 的地方。同样在这个 dll 中,我有一个扩展方法来注册映射:

 public static class MappingServiceExtension
{
    public static void AddApplicationMappings(this IServiceCollection services)
    {
        var mapperConfig = new MapperConfiguration(config =>
        {
            config.AddProfile<ApplicationMapping>();
        });

        IMapper mapper = mapperConfig.CreateMapper();
        services.AddSingleton(mapper);
    }
}

然后在我的 WebAPI 项目中,在 Startup.cs 上我放的课:

  services.AddApplicationMappings();

我通常在我的服务中将它与 DI 一起使用:

  public class AppService : IAppService
 {
    private readonly IAppRepository _appRepository;
    private readonly IMapper _mapper;

    public TruckService(IAppRepository appRepository, IMapper mapper)
    {
        _appRepository = appRepository;
        _mapper = mapper;
    }
 }

我想这样使用。但当 Mapper.AssertConfigurationIsValid(); 时我遇到异常行运行,说:

'Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.'

我在这里缺少什么?问题似乎出在 Mapper.Map<IEnumerable<App>, List<App>>(src.ToList())代码行。

但是我怎样才能获得 Mapper 的实例那里不使用静态 Mapper

最佳答案

Mapper.AssertConfigurationIsValid();

这会调用静态 IMapper 实例,该实例在不使用依赖注入(inject)的情况下使用。由于您从未设置静态映射器,因此使用它将会失败。

您想要做的是在实际映射器实例(您注册为单例的实例)上调用 AssertConfigurationIsValid 。因此,您应该从映射器配置文件中删除断言,然后在 AddApplicationMappings 方法中调用它:

IMapper mapper = mapperConfig.CreateMapper();
mapper.AssertConfigurationIsValid();
services.AddSingleton(mapper);

关于c# - 将 Automapper 与 ASP.NET Core 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56228059/

相关文章:

c# - 通过 lambda 表达式传递属性名称以读取属性值

c# - 为什么在设置 DataContext 时我的验证规则没有运行?

c# - 无法启动红隼。无法绑定(bind)到已在使用的地址

c# - 如何让 AutoMapper 不缓存映射对象?

c# - 在映射时向 Automapper 提供构造函数参数

c# - SafeHandle 中 invalidHandleValue 的用途是什么?

asp.net-core - 如何排除文件在ASP.NET Core中发布?

asp.net-core - AWS API网关+Lambda : favicon issue

automapper - 如何使用AutoMapper将父级引用分配给子级中的属性

c# - ElasticSearch 查询检索书籍的所有标签