将AutoMapper注入其他层的正确方法是什么?
我读了这个博客post,但是下面的代码导致异常
An exception of type ‘AutoMapper.AutoMapperMappingException’ occurred in AutoMapper.dll but was not handled in user code
尝试在服务层中映射时.
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));
}
}
解决方法:
似乎您需要使用在容器中注册的IConfiguration对象来创建映射,如下所示:
var configuration = container.Resolve<IConfiguration>();
configuration.CreateMap<Student, StudentViewModel>();
我认为您应该在应用程序开始时执行此操作.
这是在Config方法中配置事物的更好方法(IMO):
public static void Config()
{
var configuration_store = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
var mapping_engine = new MappingEngine(configuration_store);
configuration_store.CreateMap<Student, StudentViewModel>();
var builder = new ContainerBuilder();
builder.RegisterInstance(mapping_engine).As<IMappingEngine>();
//...
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
在上一个示例中,我假设您的类仅需要访问IMappingEngine(而不是IConfiguration),因为您应该已经在Config方法(或在应用程序启动时使用某些其他配置方法)中设置了所有映射.