Reputation: 6875
I have created an extension to map my types that implemented IHaveStandardMapping
interface.
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));
}
}
And I am using it in my service.
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;
}
}
But I need to get IMapper
interface for all services.
I should use it in method
existing.MapTo<T>(_mapper);
The old versions were did not need the IMapper
interface.
Is there a short way without using IMapper
?
Upvotes: 0
Views: 398
Reputation: 3964
The static API is now deprecated. IMapper is used so you can inject the mapper in your controllers/services. I you want to you can create your own service wrapping the IMapper interface, so you can limit your dependency on the IMapper interface to one service only.
Upvotes: 1