gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:31:26 24 4
gpt4 key购买 nike

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

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


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

最佳答案

依赖注入(inject)给我的遗留项目增加了一个整体的复杂性,我只是不想处理。 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);

关于asp.net - 如何在没有依赖注入(inject)的情况下在 Asp.Net Web Api 2 中使用 AutoMapper 9.0.0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58190428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com