使用 C# 在 .NET Core 3 中的静态类中使用 AutoMapper

Shu*_*ail 2 .net c# automapper .net-core

我面临的情况是,我正在从扩展方法类的层中转移一些逻辑。问题是我想在具有扩展方法的静态类中使用自动映射器。该项目在.NET Core上运行,我无法在静态类中访问AutoMapper,就像在控制器类中通常我们使用构造函数来注入AutoMapper,但静态类没有构造函数。

有没有办法Startup.cs以任何方式调用静态类中已配置的 AutoMapper 服务?

Oli*_*ver 6

当您需要在静态方法中使用 AutoMapper 时,您只有两种可能性:

  1. 将 AutoMapper 作为附加参数提供给静态方法。
  2. 为所需的配置文件即时创建映射器。

虽然第一个是不言自明的,但第二个需要一个额外的帮助方法,这使得它更容易使用:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有了这个,你就得到了一个静态方法,可以按如下方式使用:

var dest = WithProfile<MyProfile>.Map<Destination>(source);
Run Code Online (Sandbox Code Playgroud)

但请注意,第二种方法相当繁重,并且根据调用该方法的时间量,您最好使用第一种方法。