我有一个项目,我一直在使用automapper 2.2.1。我升级到4.2.1并且完全坏了。我试着关注this
将所有对Mapper.CreateMap<Source, Target>()
的引用更改为Mapper.Initialize(cfg => { cfg.CreateMap<Source, Target>()})
。我现在坏了,我似乎无法完成它。我得到&#34; System.Reflection.ReflectionTypeLoadException未被用户代码异常处理,无法加载一个或多个要求的类型。检索LoaderExceptions属性以获取更多信息&#34;,message。我错过了什么代码如下所示:
AutomapperTypeAdapterFactory
public class AutomapperTypeAdapterFactory : ITypeAdapterFactory
{
public AutomapperTypeAdapterFactory()
{
//scan all assemblies finding Automapper Profile
var profiles = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(t => t.BaseType == typeof(Profile));
Mapper.Initialize(cfg =>
{
foreach (var item in profiles)
{
if (item.FullName != "AutoMapper.SelfProfiler`2")
cfg.AddProfile(Activator.CreateInstance(item) as Profile);
}
});
}
public ITypeAdapter Create() => new AutomapperTypeAdapter();
}
部门简介
public class DepartmentProfile : Profile
{
protected override void Configure()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Department, DepartmentDto>();
});
}
}
UnityContainer
public static class Container
{
static IUnityContainer _container = new UnityContainer();
static Container()
{
var typeAdapterFactory = _container.Resolve<ITypeAdapterFactory>();
TypeAdapterFactory.SetCurrent(typeAdapterFactory);
}
//other container resolutions....
}
答案 0 :(得分:0)
在我离开静态配置的项目中,我已经定义了一些映射配置文件(通常是每个应用层的配置文件):
public class MappingProfile : Profile
{
protected override void Configure()
{
CreateMap<Source, Destination>();
}
}
然后我配置我的IoC(在我的情况下是SimpleInjector)来查找所有配置文件并将它们添加到单个统一配置中。然后我在我的容器中注册MapperConfiguration
,以及从同一个创建的IMapper
对象:
public void ConfigureSimpleInjector(IAppBuilder app)
{
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
container.RegisterAutoMapper();
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.RegisterMvcIntegratedFilterProvider();
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
public static Container RegisterAutoMapper(this Container container)
{
var profiles = typeof(AutoMapperRegistry).Assembly.GetTypes().Where(t => typeof(Profile).IsAssignableFrom(t)).Select(t => (Profile)Activator.CreateInstance(t));
var config = new MapperConfiguration(cfg =>
{
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
});
container.Register<MapperConfiguration>(() => config);
container.Register<IMapper>(() => container.GetInstance<MapperConfiguration>().CreateMapper());
return container;
}
}
然后我可以将DI用于IMapper
(或者您可以静态存储它),以及MapperConfiguration
用于LINQ投影。