Automapper says Mapper.Map is obsolete, global mappings?

后端 未结 5 1216
孤街浪徒
孤街浪徒 2020-12-12 21:01

I had defined in my project a global Automapper configuration that would allow me to use Mapper.Map(sourceObject); in my code. (See my configu

5条回答
  •  鱼传尺愫
    2020-12-12 21:49

    This is how I've handled it.

    Create maps in a Profile, taking care to use the Profile's CreateMap method rather than Mapper's static method of the same name:

    internal class MappingProfile : Profile
    {
        protected override void Configure()
        {
            CreateMap();
        }
    }
    

    Then, wherever dependencies are wired-up (ex: Global.asax or Startup), create a MapperConfiguration and then use it to create an IMapper.

    var mapperConfiguration = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new MappingProfile());
        });
    

    Then, use the configuration to generate an IMapper:

    var mapper = mapperConfiguration.CreateMapper();
    

    Then, register that mapper with the dependency builder (I'm using Autofac here)

    builder.RegisterInstance(mapper).As();
    

    Now, wherever you need to map stuff, declare a dependency on IMapper:

    internal class ProjectService : IProjectService {
        private readonly IMapper _mapper;
        public ProjectService(IMapper mapper) {
             _mapper = mapper;
        }
        public ProjectCreate Get(string key) {
            var project = GetProjectSomehow(key);
            return _mapper.Map(project);
        }
    }
    

提交回复
热议问题