Scans assemblies and:
- adds profiles to mapping configuration
- adds value resolvers, member value resolvers, type converters to the container.
To use, with an IServiceCollection
instance and one or more assemblies:
services.AddAutoMapper(assembly1, assembly2 /*, ...*/);
or marker types:
services.AddAutoMapper(type1, type2 /*, ...*/);
This registers AutoMapper:
- As a singleton for the
MapperConfiguration
- As a transient instance for
IMapper
ITypeConverter
instances as transientIValueConverter
instances as transientIValueResolver
instances as transientIMemberValueResolver
instances as transientIMappingAction
instances as transient
Mapping configuration is static as it is the root object that can create an IMapper
.
Mapper instances are registered as transient. You can configure this with the serviceLifetime
parameter. Be careful changing this, as Mapper
takes a dependency on a factory method to instantiate the other extensions.
To map at runtime, add a dependency on IMapper
:
public class EmployeesController {
private readonly IMapper _mapper;
public EmployeesController(IMapper mapper)
=> _mapper = mapper;
// use _mapper.Map to map
}
Starting with 8.0 you can use IMapper.ProjectTo
. The old ProjectTo
is an extension method and does not have dependency injection available. Pass an IConfigurationProvider
instance directly:
var orders = await dbContext.Orders
.ProjectTo<OrderDto>(_configurationProvider)
.ToListAsync();
Or you can use an IMapper
instance:
var orders = await dbContext.Orders
.ProjectTo<OrderDto>(_mapper.ConfigurationProvider)
.ToListAsync();