如何在没有依赖注入的情况下在 Asp.Net Web Api 2 中使用 AutoMapper 9.0.0?

How to use AutoMapper 9.0.0 in Asp.Net Web Api 2 without dependency injection?

我找不到任何信息可以将此代码放入我的项目中。现在我在每个需要映射器的动作中使用它。没有依赖注入,有没有更好的方法来做到这一点?

var config = new MapperConfiguration(cfg => {
                cfg.CreateMap<Source, Dest>();
            });
            IMapper iMapper = config.CreateMapper();


            var destList= iMapper.Map<Dest[]>(sourceList);

依赖注入给我的遗留项目增加了一个整体的复杂性,我只是不想处理。 9.0 删除了 api 以静态调用它。

所以我只是对它在 8.0 中所做的事情进行了逆向工程,并为它编写了一个包装器。

public static class MapperWrapper 
{
    private const string InvalidOperationMessage = "Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.";
    private const string AlreadyInitialized = "Mapper already initialized. You must call Initialize once per application domain/process.";

    private static IConfigurationProvider _configuration;
    private static IMapper _instance;

    private static IConfigurationProvider Configuration
    {
        get => _configuration ?? throw new InvalidOperationException(InvalidOperationMessage);
        set => _configuration = (_configuration == null) ? value : throw new InvalidOperationException(AlreadyInitialized);
    }

    public static IMapper Mapper
    {
        get => _instance ?? throw new InvalidOperationException(InvalidOperationMessage);
        private set => _instance = value;
    }

    public static void Initialize(Action<IMapperConfigurationExpression> config)
    {
        Initialize(new MapperConfiguration(config));
    }

    public static void Initialize(MapperConfiguration config)
    {
        Configuration = config;
        Mapper = Configuration.CreateMapper();
    }

    public static void AssertConfigurationIsValid() => Configuration.AssertConfigurationIsValid();
}

要初始化它有一个配置方法

public static class AutoMapperConfig
{
    public static void Configure()
    {
        MapperWrapper.Initialize(cfg =>
        {
            cfg.CreateMap<Foo1, Foo2>();              
        });

        MapperWrapper.AssertConfigurationIsValid();
    }
}

只需在您的启动程序中调用它

AutoMapperConfig.Configure();

要使用它,只需在调用 Mapper 之前添加 MapperWrapper 即可。可以在任何地方调用。

 MapperWrapper.Mapper.Map<Foo2>(Foo1);