Resolving “Mapper not initialized. Call Initialize with appropriate configuration.”

Hi,

In case you’re using AutoMapper to map entity objects; something like below line of code

Mapper.Map<User, UserEntity>(user);

and if you get the exception, “Mapper not initialized. Call Initialize with appropriate configuration.“, then it means, well, that you’ve not initialized AutoMapper and need to do so before mapping entities 🙂

So in order to initialize AutoMapper and create maps, use the below code in your application. It is better to call the below method on application startup.

public static void InitializeAutoMapper()
        {
            Mapper.Initialize(x =>
                x.AddProfile<MapProfile>()
                );
        }

In the above code, ‘MapProfile’ is a custom class that I’ve added which inherits from AutoMapper.Profile class and overrides the Configure method to define custom maps required in the application. The code inside MapProfile is as shown below.

internal class MapProfile : AutoMapper.Profile
    {
        protected override void Configure()
        {
            CreateMap<DataModel.User, BusinessEntities.UserEntity>();
            CreateMap<BusinessEntities.UserEntity, DataModel.User>();
        }
    }

In case you add more entities in your application and need more maps, you can just add the CreateMap<> statements in the above Configure method as required.

Once the above code is added, AutoMapper gets initialized and the exception no longer throws while mapping objects.

Hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *