Automapper Compile Mappings asp.net core

Viewed 213

I'm using the following syntax in my asp.net core startup class to configure automapper:

services.AddAutoMapper(c => c.AllowNullCollections = true, AppDomain.CurrentDomain.GetAssemblies());

I'd like to be able to compile the mappings at startup.

According to the Automapper docs, I should be able to do so via:

var configuration = new MapperConfiguration(cfg => {});
configuration.CompileMappings();

How do I get access to the mapping configuration using AddServices syntax?

1 Answers

You can inject an instance of IConfigurationProvider from the AutoMapper assembly and configure AutoMapper this way. For example, you could use the Configure() Startup Method like this:

public void Configure(IApplicationBuilder app, IConfigurationProvider mapperConfiguration)
{
    mapperConfiguration.CompileMappings();
}

Or do it programmatically:

public void Configure(IApplicationBuilder app)
{
    var mapperConfiguration = app.ApplicationServices
                                 .GetRequiredService<IConfigurationProvider>();
    mapperConfiguration.CompileMappings();
}
Related