Click here to Skip to main content
14,453,401 members

AutoMapper 4.2.1

Rate this:
4.73 (10 votes)
Please Sign up or sign in to vote.
4.73 (10 votes)
18 Jun 2016CPOL
Migration to AutoMapper 4.2.1

Introduction

With AutoMapper 4.2.1, majority of static APIs have been removed and new instance based API is exposed. Upgrading an existing project or working on a brand new project with latest AutoMapper release will require a different approach.

In this tip, we will integrate the latest version of AutoMapper into an MVC project.

Using the Code

Install AutoMapper via Nuget Package Manager.

Image 1

Also install Autofac, to demonstrate passing of mapper object through Dependency Injection.

Image 2

First step would be to create a class inheriting from AutoMapper.Profile class. Then, override the Configure function to create mapping between different classes. There can be multiple Profile classes to group related mappings.

public class MappingProfile : Profile
    {
        protected override void Configure()
        {
            CreateMap<UserModel, UserViewModel>()
                .ForMember(x => x.UserName, opt => opt.MapFrom
                     (y => y.FirstName + " " + y.MiddleName + " " + y.LastName))
                .ForMember(x => x.UserAddress,
                    opt => opt.MapFrom(y => y.AddressLine1 + " " + y.AddressLine2 + " " + y.PinCode));
        }
    }

Next step will be to create a Configuration class where profile classes are passed to MapperConfiguration constructor. MapperConfiguration object is used to generate mapper object using CreateMapper() function.

public class AutoMapperConfig
    {
        public static IMapper Mapper;
        public static void ConfigureAutoMapper()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MappingProfile());
            });

            Mapper = config.CreateMapper();
            config.AssertConfigurationIsValid();
        }
    }

This Configuration should be executed at the start of the application. Therefore, the following code needs to be added to global.asax.cs file's Application_Start() method.

AutoMapperConfig.ConfigureAutoMapper();

Dependency Injection

Since, most of the AutoMapper API is not static, the mapper object can now be passed through Dependency Injection. I've used autofac here to demonstrate how mapper object is passed through DI.

A local IMapper variable is created within the class and constructor assigns its value from Dependency injected IMapper object.

public class DBController : Controller
{
       private readonly IDbLogger _logger;
       private readonly IMapper _mapper;

       public DBController(IDbLogger logger, IMapper mapper)
       {
           this._logger = logger;
           this._mapper = mapper;
       }
 }

The mapper object can be added to Autofac container in such a way.

builder.RegisterInstance(AutoMapperConfig.Mapper)
                .As<IMapper>()
                .SingleInstance();

Points of Interest

Now, one can have a subset of AutoMapper mapping depending upon functionality, layers, etc. and can only inject a subset wherever required.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

saurabhsharmacs
Software Developer
India India
Saurabh Sharma is a .Net Programmer.

Comments and Discussions

 
SuggestionMissing example how to map Pin
Lechuss31-Jul-18 3:36
MemberLechuss31-Jul-18 3:36 
QuestionCan this be updated for AutoMapper 5.0+? Pin
Member 1313857319-Apr-17 6:28
MemberMember 1313857319-Apr-17 6:28 
QuestionTotally lost on Dependency Injection section... Pin
panco91823-Jun-16 5:43
Memberpanco91823-Jun-16 5:43 
AnswerRe: Totally lost on Dependency Injection section... Pin
saurabhsharmacs23-Jun-16 21:07
Membersaurabhsharmacs23-Jun-16 21:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Tip/Trick
Posted 18 Jun 2016

Stats

18.6K views
359 downloads
9 bookmarked