Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to validate AutoMapper Configuration in ASP.Net Core application?

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();
like image 756
Mr. T Avatar asked Jul 26 '18 20:07

Mr. T


People also ask

How do I test AutoMapper configuration?

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 is AutoMapper configuration?

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 in asp net core?

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.


2 Answers

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.

like image 124
Mr. T Avatar answered Oct 16 '22 17:10

Mr. T


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();
}
like image 16
sarin Avatar answered Oct 16 '22 18:10

sarin