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

问题描述 投票:0回答:2

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

有没有办法以任何方式在静态类中调用已经在

Startup.cs
中配置的AutoMapper服务?

c# .net .net-core automapper
2个回答
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);
        }
    }
}

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

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

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


0
投票

感谢奥利弗提供这个解决方案 我注意到你用了

public static Func<Type, object> ServiceCtor { get; set; }

那么ServiceCtor的作用是什么?

© www.soinside.com 2019 - 2024. All rights reserved.