Logging from Automapper

We’ve been using automapper to convert objects for some time. Now I have the need for logging to help bugtracking. Below a short list of sources how we set this up.

// ConfigureServices(IServiceCollection services) stuff

services.AddTransient(serviceprovider => {
   var cfg = serviceprovider.GetService<MapperConfiguration>();
   // inject the serviceprovider so everything is available
   // and the ILogger is too
   return cfg.CreateMapper(serviceprovider.GetService);
// AutomapperConfiguration stuff

// old automapper
/* Func<ResolutionContext, ILogger> createLogger = (c) =>
   c.Mapper.ServiceCtor.Invoke(typeof(ILogger)) as ILogger; */

// new automapper 
Func<ResolutionContext, ILogger> createLogger = (c) =>
   c.Options.ServiceCtor.Invoke(typeof(ILogger)) as ILogger;

config.CreateMap<ObjectA, ObjectB>()
      .ConvertUsing((s, d, c) => {
         // important stuff removed ....
         var logger = createLogger(c);
         logger.LogWarning("Something happend");

And now you’ll need a serviceprovider when unittesting. Thank you AutoMoqCore.

var automoqer = new AutoMoqer();
var configuration = automoqer.Create<AutomapperConfiguration>();
var mapper = configuration.CreateMapper(automoqer.Create);
// now test the mapping configuration with the mapper instance

We managed to find the bugs and fixed them. We’ll be using this logging solution with automapper from now on.

[edited 11 nov 2020] new automapper has the ServiceCtor in the context Options no longer in the context Mapper, code sample edited

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:

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 )

Connecting to %s

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