问题描述
我找不到在此项目中放置此代码的任何信息.现在,我需要在每个需要映射器的操作中使用它.有没有更好的方法来执行依赖注入?
I haven't been able to find any info where to put this code inside my project. Right now I am use using this in each action I need the mapper. Is there a better way to do this with out dependency injection?
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Source, Dest>();
});
IMapper iMapper = config.CreateMapper();
var destList= iMapper.Map<Dest[]>(sourceList);
推荐答案
依赖注入给我原来不想处理的遗留项目增加了一个整体的复杂性. 9.0删除了可静态调用的api.
Dependency injection added a whole level of complexity to my legacy project that I just didn't want to deal with. 9.0 removed the api to call it staticly.
所以我只是对8.0中的工作进行了逆向工程,并为其编写了一个包装器.
So I just reverse engineered what it was doing in 8.0 and wrote a wrapper for it.
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();
}
要初始化它,请使用configure方法
To initialize it have a configure method
public static class AutoMapperConfig
{
public static void Configure()
{
MapperWrapper.Initialize(cfg =>
{
cfg.CreateMap<Foo1, Foo2>();
});
MapperWrapper.AssertConfigurationIsValid();
}
}
然后在启动时调用它
AutoMapperConfig.Configure();
要使用它,只需在Mapper调用之前添加MapperWrapper.可以在任何地方调用.
To use it just Add MapperWrapper before your Mapper call. Can be called anywhere.
MapperWrapper.Mapper.Map<Foo2>(Foo1);
这篇关于如何在没有依赖项注入的情况下在Asp.Net Web Api 2中使用AutoMapper 9.0.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!