Automapper mówi Mapper.Mapa jest przestarzała, globalne mapowania?

Zdefiniowałem w moim projekcie globalną konfigurację Automapp, która pozwoli mi używać Mapper.Map<targetType>(sourceObject); w moim kodzie. (Patrz moja konfiguracja poniżej.)

Zaktualizowałem pakiet NuGet i widzę wiadomość, że Mapper.Mapa jest przestarzała/zamortyzowana. Wróciłem do Automapp na Githubie i zobacz przykłady takie jak:

[Test]
public void Example()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<Source1, SubDest1>().FixRootDest();
        cfg.CreateMap<Source2, SubDest2>().FixRootDest();
    });

    config.AssertConfigurationIsValid();

    var mapper = config.CreateMapper();

    var subDest1 = mapper.Map<Source1, SubDest1>(new Source1 {SomeValue = "Value1"});
    var subDest2 = mapper.Map<Source2, SubDest2>(new Source2 {SomeOtherValue = "Value2"});

    subDest1.SomeValue.ShouldEqual("Value1");
    subDest2.SomeOtherValue.ShouldEqual("Value2");
}

Czy będę musiał tworzyć konfigurację w każdej metodzie, która używa mapowania?

Mój obecny globalny konfiguracja:

namespace PublicationSystem.App_Start
{
    public class AutoMapperConfig
    {
        public static void CreateMaps()
        {
            CreateProjectMaps();
        }

        private static void CreateProjectMaps()
        {
            Mapper.CreateMap<Project, ProjectCreate>();
            Mapper.CreateMap<Project, ProjectSelectable>();
            //...
        }
    }
}

aktualizacja: Dzięki coachingowi Scotta Chamberlaina stworzyłem taką klasę: {]}

    public class MkpMapperProfile : AutoMapper.Profile
    {
        protected override void Configure() 
        {
            this.CreateMap<Project, ProjectCreate>();

            this.CreateMap<Project, ProjectSelectable>();

            this.CreateMap<Project, ProjectDetails>();

            // Many Many other maps
        }
    }

Myślę, że powinienem mieć 'MapperConfiguration' w mojej klasie BaseController. Zacząłem robić coś takiego:

public partial class BaseController : Controller
{

    private MapperConfiguration mapConfig;

    public BaseController()
    {
        db = new MkpContext();
        SetMapperConfig();
    }

    private void SetMapperConfig()
    {
        mapConfig = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile<MkpMapperProfile>();
            });
    }

    public BaseController(MapperConfiguration config)
    {
        db = new MkpContext();
        this.mapConfig = config;
    }
}
Czy jestem na dobrej drodze?
Author: M Kenyon II, 2016-02-12

5 answers

Tak sobie z tym radziłem.

Twórz mapy w profilu, zwracając uwagę na użycie metody Createmap profilu, a nie statycznej metody Mappera o tej samej nazwie:

internal class MappingProfile : Profile
{
    protected override void Configure()
    {
        CreateMap<Project, ProjectCreate>();
    }
}

Następnie, wszędzie tam, gdzie zależności są podłączone (np.asax lub Startup), Utwórz konfigurację MapperConfiguration, a następnie użyj jej do utworzenia Imappera.

var mapperConfiguration = new MapperConfiguration(cfg =>
    {
        cfg.AddProfile(new MappingProfile());
    });
Następnie użyj konfiguracji, aby wygenerować IMapper:
var mapper = mapperConfiguration.CreateMapper();

Następnie zarejestruj tego mapera w kreatorze zależności (używam Autofac tutaj)

builder.RegisterInstance(mapper).As<IMapper>();

Teraz, gdziekolwiek chcesz mapować rzeczy, zadeklaruj zależność od 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, ProjectCreate>(project);
    }
}
 39
Author: Romi Petrelis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-12 20:22:02

Używam wersji 5.2.0, wsparcie dla tworzenia map w konstruktorach zamiast override configure.

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Project, ProjectDto>();
    }
}

In Global.asax.CS call like:

Mapper.Initialize(c=>c.AddProfile<MappingProfile>());
Mam nadzieję, że to pomoże.
 12
Author: zquanghoangz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-30 03:53:48

To nowość w AutoMapper 4.2. Istnieje wpis na blogu Jimmy Bogard na ten temat: Usuwanie statycznego API z AutoMapper . Twierdzi, że

[3]}interfejs IMapper jest dużo lżejszy, a podstawowy typ zajmuje się teraz tylko wykonywaniem map, usuwając wiele problemów z wątkami...

Nowa składnia: (wklejona z posta na blogu)

var config = new MapperConfiguration(cfg => {
  cfg.CreateMap<User, UserDto>();
});

Jeśli chcesz tylko "starego sposobu" na zrobienie tego. Najnowsza wersja 4.2.1 ma przywróciłem trochę tradycji. Wystarczy użyć
CreateMap<Project, ProjectCreate>();

Zamiast

Mapper.CreateMap<Project, ProjectCreate>();

Stary kod będzie działał dobrze.

 7
Author: Blaise,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-06 13:11:01
 2
Author: Nikolay Kostov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-03 05:59:31
Mapper.Initialize(cfg => {
    cfg.CreateMap<Source, Dest>();
});
 1
Author: Roberth Solís,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-29 17:09:31