AutoMapper 在 asp net core 5.0.2 中不起作用

AutoMapper doesn't work in asp net core 5.0.2

我收到一个错误,说我没有注册 AutoMapper,但我注册了,并且在另一个项目中成功使用了下面列出的配置:

System.InvalidOperationException: 'Unable to resolve service for type 'AutoMapper.Configuration.IConfiguration' while attempting to activate 'PromoAction.Services.Identity.API.Controllers.AccountController'

请帮我弄清楚如何让它在 asp net core 5 中工作。

AutoMapperConfiguration.cs

public class AutoMapperConfiguration
{
   public MapperConfiguration Configure() => new(cfg =>
   {
       cfg.CreateMap<User, ClientDTO>();
       cfg.CreateMap<UserForRegistrationDto, User>()
            .ForMember(u => u.UserName, opt => opt.MapFrom(x => x.Email))
            .ForMember(u => u.FirstName, opt => opt.MapFrom(x => x.Name))
            .ForMember(u => u.LastName, opt => opt.MapFrom(x => x.Surname));
   });
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    var config = new AutoMapperConfiguration().Configure().CreateMapper();
    services.AddSingleton(sp => config);
}

AccountController.cs

public AccountController(IMapper mapper)
{
    this._mapper = mapper;
}

问题是您没有以良好的方式注入自动映射器。

按照以下步骤操作:

  1. 安装nuget包AutoMapper.Extensions.Microsoft.DependencyInjection

  2. 创建一个新的automapper配置文件继承自配置文件class(记得添加使用AutoMapper),示例:

 public class AutoMapperProfiles : Profile
    {
        public AutoMapperProfiles()
        {

            CreateMap<User, ClientDTO>();
            CreateMap<UserForRegistrationDto, User>()
                 .ForMember(u => u.UserName, opt => opt.MapFrom(x => x.Email))
                 .ForMember(u => u.FirstName, opt => opt.MapFrom(x => x.Name))
                 .ForMember(u => u.LastName, opt => opt.MapFrom(x => x.Surname));

        }
    }

在您的启动中 class 在配置服务的方法中使用 AddAutoMapper 并提供您的启动类型

services.AddAutoMapper(typeof(Startup));

之后就可以正常注入了

public AccountController(IMapper mapper)
{
    this._mapper = mapper;
}

在他们的文档中描述了注册 Autommaper 的推荐方法:https://docs.automapper.org/en/stable/Dependency-injection.html#asp-net-core

创建映射配置文件并使用

注册
services.AddAutoMapper(profileAssembly1, profileAssembly2 /*, ...*/);

在您的情况下,您似乎注册了映射器实例,您的示例表明您注入了映射器实例,但异常表明您想要解析 IConfiguration。如果您不尝试注入 IConfiguration(未注册),请检查您的代码。