为什么Automapper的地图需要IMapper界面?

问题描述 投票:0回答:1

我创建了一个扩展来映射实现IHaveStandardMapping接口的类型。

public static class AutomapperExtensions
{
    public static TDest MapTo<TDest>(this object src, IMapper mapper) 
        where TDest: IHaveStandardMapping
    {
        return (TDest)mapper.Map(src, src.GetType(), typeof(TDest));
    }
}

并且我在服务中使用它。

public class ComponentService : IComponentService
{
    private readonly PostgresqlDataContext _context;
    private readonly IMapper _mapper;

    public ComponentService(PostgresqlDataContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<ComponentViewModel> GetComponent(string id)
    {
        var existing = await _context.Components.FirstOrDefaultAsync(s => s.Id == id);

        if (existing == null)
            throw new EntityNotFoundException("Component");

        var result = existing.MapTo<ComponentViewModel>(_mapper);

        return result;
    }
}

但是我需要为所有服务获取IMapper界面。我应该在现存方法MapTo(_mapper);中使用它。旧版本不需要IMapper接口。是否有不使用IMapper的简便方法?

c# dependency-injection automapper
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.