Dependency Injection

Examples

ASP.NET Core

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(profileAssembly1, profileAssembly2 /*, ...*/);

or marker types:

services.AddAutoMapper(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
}

AutoFac

There is a third-party NuGet package you might want to try.

Also, check this blog.

Other DI engines

Low level API-s

AutoMapper supports the ability to construct Custom Value Resolvers, Custom Type Converters, and Value Converters using static service location:

var configuration = new MapperConfiguration(cfg =>
{
    cfg.ConstructServicesUsing(ObjectFactory.GetInstance);

    cfg.CreateMap<Source, Destination>();
});

Or dynamic service location, to be used in the case of instance-based containers (including child/nested containers):

var mapper = new Mapper(configuration, childContainer.GetInstance);

var dest = mapper.Map<Source, Destination>(new Source { Value = 15 });

Queryable Extensions

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.