Reputation: 775
I am working with a ASP.NET Core WebAPI and I want to do CRUD for my objects called "Item". I am using EF Core to work with a SQL Database and I have two models that represents my objects.
My HTTP GET one and HTTP GET many methods works in such way that it
Get ItemRepository instance
Fetch one or more ItemEntity
Map it to ItemDto by using AutoMapper This is initalized in my constructor such as
m_itemDtoMapper = new Mapper(new MapperConfiguration(cfg => cfg.CreateMap<ItemEntity, ItemDto>()));
And in my WebAPI method I map it to a ItemDto with the following line (for the GET many case):
var itemDtos = m_itemDtoMapper.Map<IEnumerable<ItemEntity>, ICollection<ItemDto>>(items);
This works well and the AutoMapper is very powerful. The questions I have now is:
Upvotes: 1
Views: 7933
Reputation: 328
In your example, it seems that you initialize each time a new mapper instance. I would suggest you go along with dependency injection and make use of AutoMapper Mapping Profiles.
You can do it in three simple steps and I think it answers both of your questions:
Step 1: Simply create a new class called MappingProfile or something similar:
public class MappingProfile: Profile
{
public MappingProfile()
{
CreateMap<User, AuthenticateDto>(); // One Way
CreateMap<User, UserDto>().ReverseMap(); // Reverse
}
}
Step 2: Register Automapper in Startup.cs
// Register AutoMapper
services.AddAutoMapper(Assembly.GetExecutingAssembly());
Step 3: Consume your mapper over DI
public UserService(IMapper mapper) {
_mapper = mapper;
}
// call it as you already did
_mapper.Map<User, UserDto>(user);
Hopefully it helps you :)
Upvotes: 6