aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline/Services/Mapper/GenericMapper.cs
blob: 4dd44828832612786919e427fe7dbc4dbd25b3ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Timeline.Services.Mapper
{
    class GenericMapper : IGenericMapper
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly AutoMapper.IMapper _autoMapper;

        public GenericMapper(IServiceProvider serviceProvider, AutoMapper.IMapper autoMapper)
        {
            _serviceProvider = serviceProvider;
            _autoMapper = autoMapper;
        }

        public TDestination AutoMapperMap<TDestination>(object source)
        {
            return _autoMapper.Map<TDestination>(source);
        }

        public async Task<TDestination> MapAsync<TSource, TDestination>(TSource source, IUrlHelper urlHelper, ClaimsPrincipal? user)
        {
            var mapper = _serviceProvider.GetService<IMapper<TSource, TDestination>>();

            if (mapper is not null)
            {
                return await mapper.MapAsync(source, urlHelper, user);
            }

            return _autoMapper.Map<TSource, TDestination>(source);
        }
    }
}