繁体   English   中英

具有依赖注入的 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 model 和我创建的各种 DTO 模型。

这是我拥有的示例配置文件 model:

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

我的 DTO 模型具有我的用户 Model 所具有的所有字段,这些字段是我不想在 UI 上显示的。

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

我也尝试在CreateMap() ) 上使用.ReverseMap() ,但这也不起作用。

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

        private readonly IMapper _mapper;

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

使用以下代码在该服务内部吐出错误: _mapper.Map<UserCustomerDto>(user)

我对 dotnet 核心和 C# 相当陌生,所以任何帮助都将不胜感激。 谢谢你,我希望这足以为我指明正确的方向。

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

我认为您尚未将自动映射器配置文件注册到服务容器中。

dotnet core 的设置在这里

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

为名为AutoMapper.Extensions.Microsoft.DependencyInjection的 dotnet 核心添加额外的 nuget package

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

services.AddAutoMapper(Assembly.GetExecutingAssembly());

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM