Reputation: 177
I haveBusinessLayer, DTO library,DataService, EntityModel(wher EDMX sits)
, DTO library refers to both business and data layer. I am trying to implement automapper
in data layer, want to map entity object to DTO object and return DTO from the dataService
library.
Currently am doing this way
public class DataService
{
private MapperConfiguration config;
public DataService()
{
IMapper _Mapper = config.CreateMapper();
}
public List<Dto.StudentDto> Get()
{
using(var context = new DbContext().GetContext())
{
var studentList = context.Students.ToList();
config = new MapperConfiguration(cfg => {
cfg.CreateMap<Db.Student, Dto.StudentDto>();
});
var returnDto = Mapper.Map<List<Db.Student>, List<Dto.StudentDto>>(studentList);
return returnDto;
}
}
}
How can I move all the mappings to one class and automapper should initialize automatically when call to dataserive is made?
Upvotes: 2
Views: 7292
Reputation: 169200
Is it good practice to use AutoMapper in data layer?
Yes.
How can I move all the mappings to one class and automapper should initialize automatically when call to dataserive is made?
You could just create a static class that creates the mappings once:
public static class MyMapper
{
private static bool _isInitialized;
public static Initialize()
{
if (!_isInitialized)
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Db.Student, Dto.StudentDto>();
});
_isInitialized = true;
}
}
}
Make sure that you use this class in your data service:
public class DataService
{
public DataService()
{
MyMapper.Initialize();
}
public List<Dto.StudentDto> GetStudent(int id)
{
using (var context = new DbContext().GetContext())
{
var student = context.Students.FirstOrDefault(x => x.Id == id)
var returnDto = Mapper.Map<List<Dto.StudentDto>>(student);
return returnDto;
}
}
}
Dependending on how you actually host the DAL, you might be able to call the Initialize()
method of your custom mapper class from the Main()
method of an executable or from somewhere else than the constructor of your DataService
class.
Upvotes: 8
Reputation: 1687
Use AutoMapper.Mapper.CreateMap
on OnAppInitialize
. You can do the implementation of course in an own static
class
for better style.
There is really no more magic in this - because you only have to register (CreateMap
) the mappings one time.
initialize automatically when call to dataserive is made?
You can of course register it too in the constructor.
Here you can take a look at another sample - how to use register in one or two of many extended ways.
In the end AutoMapper
should make your life easier and not harder. In my opinion the best way is to register everything at one point - when starting the application.
But you also can do it on demand like seperating each CreateMap
in the constructor.
Both ways - just make sure you just call it once.
Upvotes: 1