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
AutoMapper via Nuget Package Manager.
Autofac, to demonstrate passing of mapper object through Dependency Injection.
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()
.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 object is used to generate mapper object using
public class AutoMapperConfig
public static IMapper Mapper;
public static void ConfigureAutoMapper()
var config = new MapperConfiguration(cfg =>
Mapper = config.CreateMapper();
Configuration should be executed at the start of the application. Therefore, the following code needs to be added to global.asax.cs file's
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
IMapper variable is created within the class and constructor assigns its value from Dependency injected
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.
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.