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!

Advertisements

About Amogh Natu

Technology enthusiast, Associate Consultant @ Microsoft, music lover, love my guitar, Microsoft.NET, ASP.NET, C#.NET Professional.
This entry was posted in .NET, General and tagged , , , , , , , , , . Bookmark the permalink.

Your comments or opinions.....

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s