6

I am trying to implement AutoMapper in an ASP.NET Core MVC application using the techniques described in https://lostechies.com/jimmybogard/2016/07/20/integrating-automapper-with-asp-net-core-di.

Here is my startup.cs

public IServiceProvider ConfigureServices(IServiceCollection services)
{
 …
    services.AddMvc();

    services.AddAutoMapper();

…

    // Autofac configuration
    return ConfigureAutofacContainer(services);
}

Here is my AutoMapper.Profile implementation

public class AutoMapperProfile_NetCore_DtoFromDao : Profile
{
    #region ctor

    public AutoMapperProfile_NetCore_DtoFromDao()
    {
        CreateMaps();
    }

    #endregion

    #region Methods

    protected void CreateMaps()
    {
        if (Mapper.Configuration.FindTypeMapFor(typeof(AddressType),
                                                typeof(AddressTypeDto)) == null)
            CreateMap<AddressType, AddressTypeDto>();

        Mapper.Configuration.AssertConfigurationIsValid();
    }
}

AutoMapperProfile_NetCore_DtoFromDao.CreateMaps() is being called by ServiceCollectionExtensions.AddAutoMapperClasses():

public static class ServiceCollectionExtensions
{
    …
    private static void AddAutoMapperClasses(IServiceCollection services,
               Action<IMapperConfigurationExpression> additionalInitAction, 
               IEnumerable<Assembly> assembliesToScan)
    {
        …
        Mapper.Initialize(cfg =>
        {
            additionalInitAction(cfg);

           foreach (var profile in profiles)
            {
                cfg.AddProfile(profile);
            }
        });
        …
    }
}

I’m getting the following exception:

An exception of type 'System.InvalidOperationException' occurred in AutoMapper.dll but was not handled in user code

Q - Is this due to the profile calling Mapper.Configuration.FindTypeMapFor() during Mapper.Initialization()?

Q - Is it possible to test for an existing mapping configuration before adding one during initialzation?

System.InvalidOperationException was unhandled by user code
HResult=-2146233079 Message=Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance. Source=AutoMapper
StackTrace: at AutoMapper.Mapper.get_Configuration() at Dna.NetCore.Core.BLL.Mappers.AutoMapperProfile_NetCore_DtoFromDao.CreateMaps() in C:\Src\AutoMapper.Extensions.Microsoft.DependencyInjection\src\Dna.NetCore.Core.BLL\Mappers\AutoMapperProfile_NetCore_DtoFromDao.cs:line 22 at Dna.NetCore.Core.BLL.Mappers.AutoMapperProfile_NetCore_DtoFromDao..ctor() in C:\Src\AutoMapper.Extensions.Microsoft.DependencyInjection\src\Dna.NetCore.Core.BLL\Mappers\AutoMapperProfile_NetCore_DtoFromDao.cs:line 13 InnerException:

1 Answer 1

9

OK. A few things here. Your AutoMapper config, the easiest way to build this is just:

services.AddAutoMapper(typeof(Startup));

That scans the assembly from the Startup class for Profiles, and automatically adds them using Mapper.Initialize. DO NOT call Mapper.Initialize after this.

Next, your profile. You're doing a lot of things you shouldn't. First, your profile is calling AssertConfigurationIsValid - don't. Next, it's checking for existing TypeMaps - don't. Just call the base CreateMap method, that's it.

Finally, you've got an extra AddAutoMapperClasses call. Don't use that. Get rid of it. You just need the "services.AddAutoMapper". The AddAutoMapper method calls Mapper.Initialize, with the Profile classes found in the assembly you've passed in.

Sign up to request clarification or add additional context in comments.

2 Comments

If one is using AutoMapper in a class library-based Service and testing it via xUnit tests then where should we do the "services.AddAutoMapper" injection? In the start of the xUnit test fixture? This is a .NET Core class library xUnit project as many examples out there are for .NET Framework usage. Thanks.
Here's what I did: lostechies.com/jimmybogard/2016/10/24/… basically made it part of the fixture static setup to call the "Startup" configuration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.