AutoMapper implementation in ASP.NET Core MVC

匆匆过客 提交于 2020-01-03 11:33:15

问题


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:


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.



来源:https://stackoverflow.com/questions/40114996/automapper-implementation-in-asp-net-core-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!