【问题标题】:How to use AutoMapper 9.0.0 in Asp.Net Web Api 2 without dependency injection?如何在没有依赖注入的情况下在 Asp.Net Web Api 2 中使用 AutoMapper 9.0.0?
【发布时间】:2019-10-01 18:30:20
【问题描述】:

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

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


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

【问题讨论】:

  • @LucianBargaoanu 根据那篇文章,我创建了一个引导程序类,该类具有一个包含我在问题中的代码的初始化方法,然后在我的 Global.asax.cs 文件中调用该初始化方法。如何在我的控制器中访问它?谢谢。

标签: asp.net asp.net-web-api2 automapper


【解决方案1】:

依赖注入增加了我不想处理的遗留项目的复杂性。 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);

【讨论】:

    猜你喜欢
    • 2020-12-08
    • 2018-12-16
    • 2018-03-24
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 2017-10-22
    • 2013-12-04
    • 1970-01-01
    相关资源
    最近更新 更多