Search code examples
c#.net.net-coreautomapper

Using AutoMapper inside a static class in .NET Core 3 with C#


I am in a situation where I am shifting some logic from a layer in an extension method class. Problem is that I want to use auto mapper in that Static class having extension methods. The project is running on .NET Core, I am not able to get access to AutoMapper in the static class, like in the controller classes normally we use the constructor to inject the AutoMapper, but static classes do not have constructors.

Is there any way to call the AutoMapper service that is already configured in the Startup.cs, in a static class in any way?


Solution

  • When you need to use AutoMapper within a static method you only have two possibilities:

    1. Give AutoMapper as additional argument into your static method.
    2. Create a mapper on-the-fly for the desired Profile.

    While the first one is quite self-explanory, the second one needs an additional helper method, that makes it easier to use:

    using System;
    
    namespace AutoMapper
    {
        public static class WithProfile<TProfile> where TProfile : Profile, new()
        {
            private static readonly Lazy<IMapper> MapperFactory = new Lazy<IMapper>(() =>
            {
                var mapperConfig = new MapperConfiguration(config => config.AddProfile<TProfile>());
                return new Mapper(mapperConfig, ServiceCtor ?? mapperConfig.ServiceCtor);
            });
    
            public static IMapper Mapper => MapperFactory.Value;
    
            public static Func<Type, object> ServiceCtor { get; set; }
    
            public static TDestination Map<TDestination>(object source)
            {
                return Mapper.Map<TDestination>(source);
            }
        }
    }
    

    With this available you got a static method, that can be used as follows:

    var dest = WithProfile<MyProfile>.Map<Destination>(source);
    

    But be aware that this second approach is quite heavy and depending on the amount of time the method will be called you should better use the first approach.