Beispiel #1
0
        public TDestination Map <TSource, TDestination>(ResolutionContext parentContext, TSource source)
        {
            var destinationType = typeof(TDestination);
            var sourceType      = typeof(TSource);
            var typeMap         = ConfigurationProvider.ResolveTypeMap(source, null, sourceType, destinationType);
            var context         = parentContext.CreateTypeContext(typeMap, source, null, sourceType, destinationType);

            return((TDestination)((IMappingEngineRunner)this).Map(context));
        }
Beispiel #2
0
        object IMappingEngineRunner.Map(ResolutionContext context)
        {
            try
            {
                var contextTypePair = new TypePair(context.SourceType, context.DestinationType);

                Func <TypePair, IObjectMapper> missFunc =
                    tp => ConfigurationProvider.GetMappers().FirstOrDefault(mapper => mapper.IsMatch(context));

                var mapperToUse = _objectMapperCache.GetOrAdd(contextTypePair, missFunc);
                if (mapperToUse == null || (context.Options.CreateMissingTypeMaps && !mapperToUse.IsMatch(context)))
                {
                    if (context.Options.CreateMissingTypeMaps)
                    {
                        var typeMap = ConfigurationProvider.CreateTypeMap(context.SourceType, context.DestinationType);
                        context = context.CreateTypeContext(typeMap, context.SourceValue, context.DestinationValue,
                                                            context.SourceType, context.DestinationType);
                        mapperToUse = missFunc(contextTypePair);
                        if (mapperToUse == null)
                        {
                            throw new AutoMapperMappingException(context, "Unsupported mapping.");
                        }
                        _objectMapperCache.AddOrUpdate(contextTypePair, mapperToUse, (tp, mapper) => mapperToUse);
                    }
                    else
                    {
                        if (context.SourceValue != null)
                        {
                            throw new AutoMapperMappingException(context,
                                                                 "Missing type map configuration or unsupported mapping.");
                        }
                        return(ObjectCreator.CreateDefaultValue(context.DestinationType));
                    }
                }

                return(mapperToUse.Map(context, this));
            }
            catch (AutoMapperMappingException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new AutoMapperMappingException(context, ex);
            }
        }