private async Task <IMapper> GetMapperAsync(Type entityType, Type dtoType, MappingDirection direction) { var cacheKey = GetCacheKey(entityType, dtoType); var itemFactory = new Func <MapperItem>(() => { var autoMapper = direction == MappingDirection.Entity2Dto ? GetMapper(entityType, dtoType) : GetMapper(dtoType, entityType); var cacheItem = new MapperItem(dtoType, direction, autoMapper); return(cacheItem); }); IMapper mapper = null; var mappers = await InternalCache.GetAsync(cacheKey, () => { var cacheItem = itemFactory(); mapper = cacheItem.Mapper; return(Task.FromResult(new List <MapperItem>() { cacheItem })); }); // if the mapper was created during the cache creation - return it without search if (mapper != null) { return(mapper); } // if mapper already cached - return from cache var cacheItem = mappers.FirstOrDefault(m => m.Direction == direction && m.DtoType == dtoType); if (cacheItem != null) { return(cacheItem.Mapper); } // cache exists but it doesn't contain mapper for specified DTO - create it and update cache cacheItem = itemFactory(); mappers.Add(itemFactory()); await InternalCache.SetAsync(cacheKey, mappers); return(cacheItem.Mapper); }
public void MapProperties(S source, T target, bool failIfNotMatched = true) { foreach (PropertyInfo property in source.GetType() .GetProperties() .Where(c => !IgnoreList.Contains(c.Name))) { try { var sourceField = new MapperItem(property, source); var targetField = new MapperItem(MatchToTarget(property), target); targetField.Assign(sourceField.Convert(targetField.Type)); } catch (TargetNotMatchedException noMatch) { if (failIfNotMatched) { throw noMatch; } } } }