Building on Ignas's solution, with the latest AutoMapper.Extensions.Microsoft.DependencyInjection
you can now also simplify a bit using either the Action<IMapperConfigurationExpression>
or Action<IServiceProvider, IMapperConfigurationExpression>
overloads depending on if you need the service provider to resolve additional dependencies.
Though with the latter there is an ambiguous overload with params Assembly[]
and params Type[]
, and you must also specify the assembly or a type in the assembly where the mapper configuration is defined which will be important for resolving any dependent IValueResolver or other Automapper types used by the profile.
See also https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/src/AutoMapper.Extensions.Microsoft.DependencyInjection/ServiceCollectionExtensions.cs
Example:
The following can be added to startup with the domain details tucked away in another service extension class in a separate assembly:
// Startup.cs
// // IServicesCollection services
// ...
services.AddAutoMapper((serviceProvider, mapperConfiguration) =>
{
services.RegisterYourProfiles(serviceProvider, mapperConfiguration);
}, services.GetYourProfileAssembly();
// In another extension method in your domain assembly:
public static void RegisterYourMapperProfiles(this IServiceCollection services, IServiceProvider serviceProvider,
IMapperConfigurationExpression mapperConfiguration)
{
// You can use the serviceProvider to resolve any dependency of your
// custom profile classes that need to be part of DI
mapperConfiguration.AddProfile(new CustomMappingProfile());
}
public static Assembly GetYourProfileAssembly(this IServiceCollection services)
{
return typeof(CustomMappingProfile).Assembly;
}
Each domain module/assembly can have its own extension method to abstract away the details of the mapper classes.
If you don't need the serviceProvider you can opt for the simpler overload that just passes the IMapperConfigurationExpression
:
// IServicesCollection services
services.AddAutoMapper((mapperConfiguration) =>
{
services.RegisterYourProfiles(mapperConfiguration);
},
services.GetYourProfileAssembly();
);
After writing this it is arguable if this is simpler than the manual setup suggested by Ignas, but it is a way to use AddAutoMapper and still allow DI.
I also agree it is preferable to keep your profiles clean and free of other dependencies, but there may be a source -> destination mapping strategy for some of your destination fields that you want to keep free of Automapper framework dependencies and have the freedom to do a plug and play style via interfaces and DI.
IMappingAction
: docs.automapper.org/en/latest/…