【发布时间】:2020-04-22 10:03:00
【问题描述】:
将 AutoMapper 注入其他层的正确方法是什么?
我看了这篇博客post,但是这段代码导致下面的异常
AutoMapper.dll 中出现“AutoMapper.AutoMapperMappingException”类型的异常,但未在用户代码中处理
在服务层尝试映射时。
List<StudentViewModel> list2 = _mapper.Map<List<StudentViewModel>>(list);
我的 AutoFac 配置如下:
public static class DependencyRegistration
{
public static void Config()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<TypeMapFactory>().As<ITypeMapFactory>();
builder.RegisterType<ConfigurationStore>().As<ConfigurationStore>().WithParameter("mappers", MapperRegistry.Mappers).SingleInstance();
builder.Register((ctx, t) => ctx.Resolve<ConfigurationStore>()).As<IConfiguration>().As<IConfigurationProvider>();
builder.RegisterType<MappingEngine>().As<IMappingEngine>();
//...
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
【问题讨论】:
-
您是否在要转换的类型之间创建了映射?
-
异常信息是什么?
-
@YacoubMassad 是的,我创建了配置文件类并注册了它们。
-
@YacoubMassad {"缺少类型映射配置或不支持的映射。\r\n\r\n映射类型:\r\nStudent -> StudentViewModel\r\nDomainModels.Student -> ViewModels.StudentViewModel\r \n\r\n目标路径:\r\nList`1[0]\r\n\r\n源值:\r\nSystem.Data.Entity.DynamicProxies.Student_56CF505FEBA6F48D4BC49099754F9D134C329E2A4B8BCB2B62D9E22D00950B16"}
-
你能显示你创建地图的代码吗?
标签: c# asp.net-mvc dependency-injection automapper autofac