Random “Missing type map configuration or unsupported mapping.” Error in Automapper

混江龙づ霸主 提交于 2019-12-04 06:11:32

问题


Please see this post for the solution.

Ok, I finally figured it out. The: AppDomain.CurrentDomain.GetAssemblies() piece of my code sometimes does not get my mapping assembly so while it is missing I get an error. Replacing this code by forcing the app to find all assemblies solved my problem.

My Entity:

    /// <summary>
    /// Get/Set the name of the Country
    /// </summary>
    public string CountryName { get; set; }

    /// <summary>
    /// Get/Set the international code of the Country
    /// </summary>
    public string CountryCode { get; set; }

    /// <summary>
    /// Get/Set the coordinate of the Country
    /// </summary>
    public Coordinate CountryCoordinate { get; set; }

    /// <summary>
    /// Get/Set the cities of the country
    /// </summary>
    public virtual ICollection<City> Cities
    {
        get
        {
            if (_cities == null)
            {
                _cities = new HashSet<City>();
            }

            return _cities;
        }
        private set
        {
            _cities = new HashSet<City>(value);
        }
    }

My DTO:

    public Guid Id { get; set; }

    public string CountryName { get; set; }

    public string CountryCode { get; set; }

    public string Lattitude { get; set; }

    public string Longtitude { get; set; }

    public List<CityDTO> Cities { get; set; }

My Configuration

        // Country => CountryDTO
        var countryMappingExpression = Mapper.CreateMap<Country, CountryDTO>();
        countryMappingExpression.ForMember(dto => dto.Lattitude, mc => mc.MapFrom(e => e.CountryCoordinate.Lattitude));
        countryMappingExpression.ForMember(dto => dto.Longtitude, mc => mc.MapFrom(e => e.CountryCoordinate.Longtitude));

In Global.asax Application_Start I have:

        Bootstrapper.Initialise();

And in Bootstrapper I have:

public static class Bootstrapper
{
    private static IUnityContainer _container;

    public static IUnityContainer Current
    {
        get
        {
            return _container;
        }
    }

    public static void Initialise()
    {
        var container = BuildUnityContainer();

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }

    private static IUnityContainer BuildUnityContainer()
    {
        _container = new UnityContainer();

        _container.RegisterType(typeof(BoundedContextUnitOfWork), new PerResolveLifetimeManager());

        _container.RegisterType<ICountryRepository, CountryRepository>();  

        _container.RegisterType<ITypeAdapterFactory, AutomapperTypeAdapterFactory>(new ContainerControlledLifetimeManager());

        _container.RegisterType<ICountryAppService, CountryAppServices>(); 

        EntityValidatorFactory.SetCurrent(new DataAnnotationsEntityValidatorFactory());
        var typeAdapterFactory = _container.Resolve<ITypeAdapterFactory>();
        TypeAdapterFactory.SetAdapter(typeAdapterFactory);

        return _container;
    }
}

Where my adapter is:

public class AutomapperTypeAdapter : ITypeAdapter
{
    public TTarget Adapt<TSource, TTarget>(TSource source)
        where TSource : class
        where TTarget : class, new()
    {
        return Mapper.Map<TSource, TTarget>(source);
    }

    public TTarget Adapt<TTarget>(object source) where TTarget : class, new()
    {
        return Mapper.Map<TTarget>(source);
    }
}

And AdapterFactory is:

    public AutomapperTypeAdapterFactory()
    {
        //Scan all assemblies to find an Auto Mapper Profile
        var profiles = AppDomain.CurrentDomain
                                .GetAssemblies()
                                .SelectMany(a => a.GetTypes())
                                .Where(t => t.BaseType == typeof(Profile));

        Mapper.Initialize(cfg =>
        {
            foreach (var item in profiles)
            {
                if (item.FullName != "AutoMapper.SelfProfiler`2")
                    cfg.AddProfile(Activator.CreateInstance(item) as Profile);
            }
        });
    }

So I randomly get a "Missing type map configuration or unsupported mapping." error pointing:

    public TTarget Adapt<TTarget>(object source) where TTarget : class, new()
    {
        return Mapper.Map<TTarget>(source);
    }

While this error occurs randomly it is hard to debug and see what happens. I have searched a lot with no proper solution.

The error goes like:

Missing type map configuration or unsupported mapping.

Mapping types: Country -> CountryDTO MyApp.Domain.BoundedContext.Country -> MyApp.Application.BoundedContext.CountryDTO

Destination path: List`1[0]

Source value: MyApp.Domain.BoundedContext.Country

My project is an MVC 3 project with Automapper 2.2 and Unity IoC..

I will appreciate any idea, advice or solution and thanks for your answers.


回答1:


If you use Mapper.AssertConfigurationIsValid(); you would get bit more detailed info:

Unmapped members were found. Review the types and members below. Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type

In any case, you have to have mapped all properties of destination model. You were missing CityDTO and Id. Here:

Mapper.CreateMap<City, CityDTO>();

Mapper.CreateMap<Country, CountryDTO>()
    .ForMember(dto => dto.Id, options => options.Ignore())
    .ForMember(dto => dto.Longtitude, mc => mc.MapFrom(e => e.CountryCoordinate.Longtitude))
    .ForMember(dto => dto.Lattitude, mc => mc.MapFrom(e => e.CountryCoordinate.Lattitude));

Maybe you would need some additional mapping on City-CityDTO, as you did not specify them.




回答2:


For me this error had to do with where I put my CreateMap<>() call. I had put it in the static initializer for my DTO. When I moved the CreateMap<>() call to somewhere less cute, everything worked fine.



来源:https://stackoverflow.com/questions/14934809/random-missing-type-map-configuration-or-unsupported-mapping-error-in-automap

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