AutoMapper best practices - Should I be asking the DAO for information to fulfill mapping from DTO to domain object?

蓝咒 提交于 2019-12-10 14:47:26

问题


/// <summary>
///     Initialize the AutoMapper mappings for the solution.
///     http://automapper.codeplex.com/
/// </summary>
public static void CreateAutoMapperMaps()
{
    IDaoFactory daoFactory = DependencyResolver.Current.GetService<IDaoFactory>();

    Mapper.CreateMap<Error, ErrorDto>()
            .ReverseMap();

    IPlaylistDao playlistDao = daoFactory.GetPlaylistDao();
    IUserDao userDao = daoFactory.GetUserDao();

    Mapper.CreateMap<Playlist, PlaylistDto>();
    Mapper.CreateMap<PlaylistDto, Playlist>()
            .ForMember(playlist => playlist.User, opt => opt.MapFrom(playlistDto => userDao.Get(playlistDto.UserId)));

    Mapper.CreateMap<PlaylistItem, PlaylistItemDto>();
    Mapper.CreateMap<PlaylistItemDto, PlaylistItem>()
            .ForMember(playlistItem => playlistItem.Playlist,
                        opt => opt.MapFrom(playlistItemDto => playlistDao.Get(playlistItemDto.PlaylistId)));

    Mapper.CreateMap<ShareCode, ShareCodeDto>().ReverseMap();

    Mapper.CreateMap<User, UserDto>().ReverseMap();
    Mapper.CreateMap<Video, VideoDto>().ReverseMap();

    Mapper.AssertConfigurationIsValid();
}

A friend is telling me that it is bad practice for AutoMapper to rely on DAOs to fulfill mappings from DTO to Domain.

I don't understand why this is bad practice nor do I understand how it would be possible to effectively work on my domain object with null references.

Can anyone explain? Thanks


回答1:


This is mostly my opinion based on my experience and reading. Others might disagree. If you hold to a strict domain entity separation from other tiers, then using AutoMapper to populate your domain entity (DE) would be considered bad. Strict DE design generally will not expose its properties in settable form. Your entity will jealously control how the data is set with careful validation that vets the input before permitting it to become part of the entity. Often this takes the form of only making methods available publicly. I feel this is a useful mode for critical systems and very complex business logic.

My problem with the above model is that in many situations, it is overkill and will result in way too many copies of your domain data. Do you really want to map a DTO loaded from your datasource to your DE, then map another DTO from your DE to your view? Painful, with more room for bugs.

For smaller, simpler systems, I think it makes more sense to make your DE map to the data store with a good ORM solution, use an Onion Architecture to manage dependencies, and map your DE to view models as appropriate. This is where AutoMapper is very helpful.



来源:https://stackoverflow.com/questions/22138669/automapper-best-practices-should-i-be-asking-the-dao-for-information-to-fulfil

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!