Glo*_*Jim 2 asp.net automapper asp.net-web-api2
我一直无法找到任何信息将此代码放入我的项目中。现在我在需要映射器的每个操作中都使用它。有没有更好的方法来做到这一点而不依赖注入?
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Source, Dest>();
});
IMapper iMapper = config.CreateMapper();
var destList= iMapper.Map<Dest[]>(sourceList);
Run Code Online (Sandbox Code Playgroud)
依赖注入给我的遗留项目增加了一个我不想处理的复杂程度。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();
}
Run Code Online (Sandbox Code Playgroud)
初始化它有一个配置方法
public static class AutoMapperConfig
{
public static void Configure()
{
MapperWrapper.Initialize(cfg =>
{
cfg.CreateMap<Foo1, Foo2>();
});
MapperWrapper.AssertConfigurationIsValid();
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的启动中调用它
AutoMapperConfig.Configure();
Run Code Online (Sandbox Code Playgroud)
要使用它,只需在 Mapper 调用之前添加 MapperWrapper。可以在任何地方调用。
MapperWrapper.Mapper.Map<Foo2>(Foo1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2895 次 |
| 最近记录: |