具有依赖注入的 AutoMapper 不映射配置文件?

AutoMapper with Dependency Injection Not Mapping Profiles?

所以这是我的第一个 Stack Overflow 问题,我希望我能提供足够的帮助细节。我正在尝试将 AutoMappper 与带有依赖项注入的 dotnet 3.1 一起使用,但它似乎并没有按照它所说的方式注册我的地图。

我收到的错误:

AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Mapping types:
User -> UserCustomerDto

在我的 Startup.cs 我有: services.AddAutoMapper(typeof(Startup));IServiceCollection 区域

我已经创建了 User 模型和各种 DTO 模型。

这是我的个人资料模型示例:

    public class UserCustomerProfile : Profile
    {
        public UserCustomerProfile()
        {
            CreateMap<User, UserCustomerDto>();
            CreateMap<UserCustomerDto, User>();
        }
    }

我的 DTO 模型具有我的用户模型具有的所有字段减去一些,我不想显示给 UI 的字段。

文档很难理解,因为有非依赖注入示例以及 9.0 之前的示例,其中在项目启动期间需要配置。

我也试过在 CreateMap() 上使用 .ReverseMap(),但也没有用。

我正在使用的服务中注入:

        private readonly IMapper _mapper;

        public UserService(IMapper mapper)
        {
            _mapper = mapper;
        }

错误出现在该服务内部,代码如下:_mapper.Map<UserCustomerDto>(user)

我是 dotnet core 和 C# 的新手,所以非常感谢您的帮助!谢谢你,我希望这能提供足够的信息,为我指明正确的方向。

更新: 将 Profile 模型移动到与我的 Startup 相同的项目时,一切正常。现在我只需要知道如何添加对包含我的 Profile 模型的其他项目的引用。或者也许我不能?最好将它保存在我的其他模型所在的模型项目中。

我认为您还没有将您的自动映射器配置文件注册到服务容器中。

dotnet 核心的设置在这里

https://docs.automapper.org/en/stable/Dependency-injection.html#asp-net-core

为名为 AutoMapper.Extensions.Microsoft.DependencyInjection

的 dotnet 核心添加额外的 nuget 包

如果您的配置文件在同一个项目中,您可以在启动时添加此代码

services.AddAutoMapper(Assembly.GetExecutingAssembly());

如果您的自动映射器配置文件在另一个项目中

// where UserCustomerProfile is any class in the other project
services.AddAutoMapper(
    Assembly.GetAssembly(typeof(UserCustomerProfile)));

它将搜索所有配置文件并将它们注册到服务列表中。