AutoMapper upgrade to v12

We use AutoMapper in almost all of our solutions. The recent new version forced us to finally refactor the way we used to resolve external dependencies. As you can read here ( the ServiceCtor was removed.


First we upgraded the AutoMapper nuget and added the dependency injection nuget as described here ( Now we kan call this code in our startup and AutoMapper will be added with all dependencies available.

services.AddAutoMapper(typeof(AppProfile), typeof(AdaptersProfile));

Configuration to Profile

We used to create files to configure an MapperConfiguration and created the Mapper from there. The code looked something like this:

// this is ** NOT ** what we want
public class AutoMapperConfiguration : MapperConfiguration {
   public static Action<IMapperConfigurationExpression> Config {
      get {
         return config => config.CreateMap< .... >
            .ConvertUsing(source, destination, context => context.Options.ServiceCtor.Invoke(typeof(ILogger)).LogWarning("something"));

The new way of using dependency injection (already introduced in v5) is to use the provided interfaces and inject the dependency into the implementing class. These interfaces are described here ( The code below shows a simple mapping with some logging.

// this is mush cleaner
public class ProfileWithLogging : Profile {
   public ProfileWithLogging() {
      CreateMap<A, B>().ConvertUsing<LoggingTypeConverter>();

public class LoggingTypeConverter : ITypeConverter<A, B> {
   private readonly ILogger _logger;
   public LoggingTypeConverter(Ilogger logger) { _logger = logger; }
   public B Convert(A source, B destination, ResolutionContext context) {
      _logger.LogInformation("Mapping A to B");

Not sure what this does to speed or memory usage. The code looks a lot cleaner and we updated to the latest version – happy coder 🙂

disclaimer – source code may not compile and is for illustration purposes – use on your own risk

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , . Bookmark the permalink.

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.