【发布时间】:2019-08-12 00:17:04
【问题描述】:
我有以下产品映射,它将调用依赖项(ProductMapService 中的 UpdateProduct)在初始映射后执行到产品子实体的映射。但是,当我执行映射过程时,我收到一个异常(没有为此对象定义无参数构造函数。)
我不确定这是在配置文件类中注入依赖项的最佳方式。谁能给我建议?
Automapper 产品简介:
namespace MyAPI.Mappers
{
public class ProductProfiles: Profile
{
private readonly IProductMapService _productMap;
public ProductProfiles(IProductMapService productMap)
{
_productMap = productMap;
CreateMap<ProductForCreationDto, Product>();
CreateMap<ProductForUpdateDto, Product>()
.ForMember(p => p.VariOptions, opt => opt.Ignore())
.AfterMap((pDto, p) => _productMap.UpdateProduct(pDto, p));
}
}
}
ProductService.cs:
namespace MyAPI.Services
{
public class ProductMapService: IProductMapService
{
private readonly IMapper _mapper;
public ProductMapService(IMapper mapper)
{
_mapper = mapper;
}
public void UpdateProduct(ProductForUpdateDto productForUpdateDto, Product productFromRepo)
{
foreach (var variOptionDto in productForUpdateDto.VariOptions)
{
if(variOptionDto.Id == 0)
{
productFromRepo.VariOptions.Add(Mapper.Map<VariOption>(variOptionDto));
}
else
{
_mapper.Map(variOptionDto, productFromRepo.VariOptions.SingleOrDefault(vo => vo.Id == variOptionDto.Id));
}
foreach (var variOptionTwoDto in variOptionDto.VariOptionTwos)
{
if(variOptionTwoDto.Id == 0)
{
productFromRepo.VariOptions.FirstOrDefault(vo => vo.Id == variOptionDto.Id).VariOptionTwos.Add(Mapper.Map<VariOptionTwo>(variOptionTwoDto));
}
else
{
_mapper.Map(variOptionTwoDto, productFromRepo.VariOptions.FirstOrDefault(vo => vo.Id == variOptionDto.Id).VariOptionTwos.SingleOrDefault(vot => vot.Id == variOptionTwoDto.Id));
}
}
}
}
}
}
在 Startup.cs 中:
services.AddAutoMapper();
services.AddSingleton<IProductMapService, ProductMapService>();
【问题讨论】:
-
谢谢@LucianBargaoanu。这就像一个魅力
标签: dependency-injection .net-core automapper