Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper implementation in ASP.NET Core MVC

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:

like image 647
RandyDaddis Avatar asked Oct 18 '16 17:10

RandyDaddis


People also ask

How AutoMapper is implemented in MVC?

First install the NuGet Package Manager in your Visual Studio IDE. Once done, go to "Tools" -> "Library Packet Manager" -> "Packet manager Console". Press Enter. This will install AutoMapper and the next time you open MVC application in Visual Studio, it will automatically add a DLL reference to the project.

Does AutoMapper work with .NET core?

AutoMapper is a ubiquitous, simple, convention-based object-to-object mapping library compatible with.NET Core. It is adept at converting an input object of one kind into an output object of a different type.

How do I use AutoMapper in .NET core?

AutoMapper Mapping ProfileTo create a mapping profile, create a class that derives from AutoMapper Profile class. Use CreateMap method to create a mapping from one type to another. CreateMap method is called twice to create 2 mappings. Employee to EditEmployeeModel and the reverse.


1 Answers

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.

like image 61
Jimmy Bogard Avatar answered Sep 25 '22 00:09

Jimmy Bogard