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.AddSingleton<MapperConfiguration,
AutomapperConfiguration>();
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