Col*_*ber 3 c# entity-framework dependency-injection automapper asp.net-core
所以这是我的第一个 Stack Overflow 问题,我希望我能提供足够的帮助细节。我正在尝试将 AutoMappper 与 dotnet 3.1 与依赖注入一起使用,但是它似乎并没有像它所说的那样注册我的地图。
我收到的错误:
AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.
Mapping types:
User -> UserCustomerDto
Run Code Online (Sandbox Code Playgroud)
在我的 Startup.cs 中,我有:services.AddAutoMapper(typeof(Startup));在该区IServiceCollection域内
我User创建了我的模型和各种 DTO 模型。
这是我拥有的示例 Profile 模型:
AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.
Mapping types:
User -> UserCustomerDto
Run Code Online (Sandbox Code Playgroud)
我的 DTO 模型具有我的用户模型所具有的所有字段,但我不想显示在 UI 中的那些字段。
文档相当难以遵循,因为有非依赖注入的示例以及在项目启动期间需要配置的 9.0 之前的示例。
我也尝试.ReverseMap()在 上使用,CreateMap()但这也不起作用。
我正在使用的服务中注入:
public class UserCustomerProfile : Profile
{
public UserCustomerProfile()
{
CreateMap<User, UserCustomerDto>();
CreateMap<UserCustomerDto, User>();
}
}
Run Code Online (Sandbox Code Playgroud)
错误所在的地方是使用以下代码的服务内部: _mapper.Map<UserCustomerDto>(user)
我对 dotnet core 和 C# 还很陌生,所以任何帮助都将不胜感激!谢谢,我希望这足以提供信息,为我指明正确的方向。
更新: 将 Profile 模型移动到与我的 Startup 相同的项目时,一切正常。现在我只需要知道如何添加对包含我的 Profile 模型的其他项目的引用。或者我不能?将它保留在我的模型项目中我的其余模型所在的位置会很好。
我认为您尚未将自动映射器配置文件注册到服务容器中。
dotnet core 的设置在这里
https://docs.automapper.org/en/stable/Dependency-injection.html#asp-net-core
为 dotnet 核心添加额外的 nuget 包,称为 AutoMapper.Extensions.Microsoft.DependencyInjection
如果您的配置文件在同一个项目中,您可以在启动时添加此代码
services.AddAutoMapper(Assembly.GetExecutingAssembly());
Run Code Online (Sandbox Code Playgroud)
如果您的自动映射器配置文件在另一个项目中
// where UserCustomerProfile is any class in the other project
services.AddAutoMapper(
Assembly.GetAssembly(typeof(UserCustomerProfile)));
Run Code Online (Sandbox Code Playgroud)
它将搜索所有配置文件并将它们注册到服务列表中。
| 归档时间: |
|
| 查看次数: |
2450 次 |
| 最近记录: |