docs/source/Dependency-injection.md
There is a NuGet package to be used with the default injection mechanism described here and used in this project.
Starting with version 13.0, AddAutoMapper is part of the core package and the DI package is discontinued.
You define the configuration using profiles. And then you let AutoMapper know in what assemblies are those profiles defined by calling the IServiceCollection extension method AddAutoMapper at startup:
services.AddAutoMapper(cfg => { }, profileAssembly1, profileAssembly2 /*, ...*/);
or marker types:
services.AddAutoMapper(cfg => { }, typeof(ProfileTypeFromAssembly1), typeof(ProfileTypeFromAssembly2) /*, ...*/);
Now you can inject AutoMapper at runtime into your services/controllers:
public class EmployeesController {
private readonly IMapper _mapper;
public EmployeesController(IMapper mapper) => _mapper = mapper;
// use _mapper.Map or _mapper.ProjectTo
}
There is a third-party NuGet package you might want to try.
Also, check this blog.
AutoMapper supports the ability to construct Custom Value Resolvers, Custom Type Converters, Value Converters, and Class-based Conditions using static service location:
var configuration = new MapperConfiguration(cfg =>
{
cfg.ConstructServicesUsing(ObjectFactory.GetInstance);
cfg.CreateMap<Source, Destination>();
}, loggerFactory);
When using AddAutoMapper, AutoMapper will automatically register implementations of the following types as ServiceLifetime.Transient from the specified assemblies:
IValueResolver<TSource, TDestination, TDestMember>IMemberValueResolver<TSource, TDestination, TSourceMember, TDestMember>ITypeConverter<TSource, TDestination>IValueConverter<TSourceMember, TDestinationMember>IDestinationFactory<TSource, TDestination>ICondition<TSource, TDestination, TMember>IPreCondition<TSource, TDestination>IMappingAction<TSource, TDestination>Starting with 8.0 you can use IMapper.ProjectTo. For older versions you need to pass the configuration to the extension method IQueryable.ProjectTo<T>(IConfigurationProvider).
Note that ProjectTo is more limited than Map, as only what is allowed by the underlying LINQ provider is supported. That means you cannot use DI with value resolvers and converters as you can with Map.