Building an ASP.Net Core 2.0 web application and can't figure out where to validate the AutoMapper configuration.
In my ConfigureServices() method, I have
services.AddAutoMapper();
And I'm registering my mappings in an Automapper Profile
public class MyAutomapperProfile : Profile
{
    public MyAutomapperProfile()
    {
        CreateMap<FooDto, FooModel>();
        CreateMap<BarDto, BarModel>();
    }
}
But it's not clear where to call
Mapper.Configuration.AssertConfigurationIsValid();
                To test our configuration, we simply create a unit test that sets up the configuration and executes the AssertConfigurationIsValid method: var configuration = new MapperConfiguration(cfg => cfg. CreateMap<Source, Destination>()); configuration. AssertConfigurationIsValid();
Where do I configure AutoMapper? ¶ Configuration should only happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.
What is AutoMapper? AutoMapper is a simple library that helps us to transform one object type into another. It is a convention-based object-to-object mapper that requires very little configuration. The object-to-object mapping works by transforming an input object of one type into an output object of a different type.
After digging around in the IMapper interface (and thanks to the documentation link provided by @LucianBargaoanu), I found exactly what I needed.
In ConfigureServices(): 
        // Adds AutoMapper to DI configuration and automagically scans the 
        // current assembly for any classes that inherit Profile 
        // and registers their configuration in AutoMapper
        services.AddAutoMapper();
The secret sauce is to add IMapper mapper as a parameter to Configure() - the parameter list is dependency-injected so you can reference any service registered in ConfigureServices()
public void Configure(IApplicationBuilder app, ... , IMapper mapper)
{
  ...
        mapper.ConfigurationProvider.AssertConfigurationIsValid();
}
Works exactly as expected.
The recommended approach (see JBogard's response) is to move this test into a unit test:
public class MappingTests
{
    private readonly IMapper _sut;
    public MappingTests() => _sut = new MapperConfiguration(cfg => { cfg.AddProfile<MyAutomapperProfile>(); }).CreateMapper();
    [Fact]
    public void All_mappings_should_be_setup_correctly() => _sut.ConfigurationProvider.AssertConfigurationIsValid();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With