How to add new maps to an existing mapper with AutoMapper (not static)

3,521 views
Skip to first unread message

Gp

unread,
Jun 8, 2016, 4:43:09 AM6/8/16
to AutoMapper-users
bvbbbb

Gp

unread,
Jun 8, 2016, 4:46:01 AM6/8/16
to AutoMapper-users
Let's suppose I have a mapper initialized somewhere in this way:

Mapper.Initialize(cfg => {
    cfg.CreateMap<Foo, Bar>();
    cfg.AddProfile<FooProfile>();
});


Is it possible to add new maps to it or to reinitialize it by adding new maps? For example:

Mapper.Initialize(cfg => {
    cfg.CreateMap<NewFoo, NewBar>();
    cfg.AddProfile<NewFooProfile>();
    // here I get the old maps and profiles
    cfg.CreateMaps(Mapper.GetOriginalMaps());      // ???
    cfg.AddProfiles(Mapper.GetOriginalProfiles()); // ???
});



Obviously I have not direct access to the original FooProfile and maps.

Another attempt I did without success is by using TypeMap:

var typeMap = Mapper.Instance.ConfigurationProvider.FindTypeMapFor<NewFoo, NewBar>();
if (typeMap != null) {
   // modify/extend it
  typeMap.ForMember(src => ...); ???
} else {
   // Add it to the current Mapper
   Mapper.Instance CreateMap<NewFoo, NewBar>().ForMember(..) ???
}


Please, help me!

Gp

Jimmy Bogard

unread,
Jun 8, 2016, 5:08:13 AM6/8/16
to automapper-users
Yes, you can do this in the latest MyGet build:

var cfg = new MapperConfigurationExpression();
cfg.CreateMap<Foo, Bar>();
cfg.AddProfile<FooProfile>();

var mapperConfig = new MapperConfiguration(cfg);
IMapper mapper = new Mapper(mapperConfig);

// later
cfg.CreateMap<NewFoo, NewBar>();
cfg.AddProfile<NewFooProfile>();
mapperConfig = new MapperConfiguration(cfg);
mapper = new Mapper(mapperConfig);


You can't do it with the static class, at the moment, but open a GitHub issue and we can track adding the Mapper.Initialize(cfg) way of doing things.

--
You received this message because you are subscribed to the Google Groups "AutoMapper-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to automapper-use...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Gp

unread,
Jun 8, 2016, 9:12:07 AM6/8/16
to AutoMapper-users
Thank you very much.


> Yes, you can do this in the latest MyGet build:

So my understanding is that, now, with v. 4.2.1 I am not able to reach the goal, isn't it?

Last but not  least: what about TypeMap, can it work?

var typeMap = Mapper.Instance.ConfigurationProvider.FindTypeMapFor<NewFoo, NewBar>();
if (typeMap != null) {
   // modify/extend it
  typeMap.ForMember(src => ...); ???
} else {
   // Add it to the current Mapper
   Mapper.Instance.CreateMap<NewFoo, NewBar>().ForMember(..) ???
}

 
thanks, again
gp

Jimmy Bogard

unread,
Jun 9, 2016, 5:14:31 AM6/9/16
to automapp...@googlegroups.com
No, because the type map does not exist. But you shouldn't need to check it, CreateMap is idempotent.
Reply all
Reply to author
Forward
0 new messages