0

I'm trying to upgrade to AutoMapper 7.0.1 which no longer uses static methods. I'm getting the following error:

Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.

I think it's coming from profiles like this which I switched to not use static methods except it still uses the static Mapper.Map<>() in the lambda expression:

public class MyProfile : Profile
{
    public MyProfile()
    {
        CreateMap<CredentialDetailDto, CredentialDetail>()
            .ForMember(x => x.Owners, opt => opt.ResolveUsing(y => 
                Mapper.Map<IList<OwnerDto>>(y.Owners)))
    }
}

How can I get an instance of the mapper to be used in place of the static Mapper.Map method?

adam0101
  • 29,096
  • 21
  • 96
  • 174

1 Answers1

1

Using Lucian's comment, I found https://stackoverflow.com/a/43259537/64279. It seems that there are overloads which will pass you a context which has the instance of IMapper.

For example:

.ForMember(x => x.Owners, opt => opt.ResolveUsing((src, dst, arg3, context) => 
    context.Mapper.Map<IList<OwnerDto>>(src.Owners)))

There are overloads for the other methods as well, such as

.AfterMap((s, d, context) =>

And

.ConvertUsing((source, dst, context) =>

You just need to supply the right number of arguments in your lambda expression.

adam0101
  • 29,096
  • 21
  • 96
  • 174
  • Ok, but why do you need this? That's what happens by default. – Lucian Bargaoanu Sep 25 '18 at 05:04
  • @LucianBargaoanu, if you mean what the code itself is doing, I didn't write it and don't know it's intention. It was written by people who probably didn't know what they were doing, but I can't be 100% sure. I'm just trying to upgrade it without breaking anything. – adam0101 Sep 25 '18 at 14:11
  • 1
    I see. Anyway, most likely it's not needed. Even if it is needed for some reason, it would look much better with MapFrom. That's what I was trying to say. But I see your point :) – Lucian Bargaoanu Sep 25 '18 at 14:49