如何在StructureMap中配置AutoMapper?遇IMapper注册异常求助
在StructureMap中正确配置AutoMapper的解决方案
嘿,我帮你排查下这个问题~你遇到的StructureMapConfigurationException是因为IMapper的注册方式有点问题,结合你用的StructureMap 3.x和AutoMapper 10.x版本,我们可以调整配置来解决这个问题:
问题分析
你当前的代码是手动创建了IMapper实例并注册,但可能因为StructureMap的注册顺序或者实例生命周期的问题,导致容器无法正确找到这个注册。另外,手动创建MapperConfiguration并直接生成IMapper也不符合AutoMapper的最佳实践——MapperConfiguration是重量级对象,应该全局单例复用。
修正后的配置代码
把你的InfrastructureRegistry改成下面这样:
public class InfrastructureRegistry : Registry { public InfrastructureRegistry() { // 1. 注册MapperConfiguration为单例(核心:只初始化一次) For<MapperConfiguration>() .Use(() => new MapperConfiguration(cfg => { cfg.AddProfile(typeof(MapperProfile)); })) .Singleton(); // 2. 通过MapperConfiguration创建IMapper并注册,同样设为单例(IMapper线程安全) For<IMapper>() .Use(ctx => ctx.GetInstance<MapperConfiguration>().CreateMapper()) .Singleton(); // 3. 扫描程序集注册其他服务 Scan( scan => { scan.TheCallingAssembly(); scan.AssemblyContainingType<IRequestService>(); scan.AssemblyContainingType<IRepositoryWrapper>(); scan.WithDefaultConventions(); }); // 手动注册服务(如果扫描没覆盖到的话) For<IRequestService>().Use<RequestService>(); For<IRepositoryWrapper>().Use<RepositoryWrapper>(); } }
关键调整点
- 单例的MapperConfiguration:确保AutoMapper的映射配置只被初始化一次,避免重复开销,这是AutoMapper官方推荐的做法。
- 通过容器上下文创建IMapper:让StructureMap负责从已注册的
MapperConfiguration生成IMapper,保证依赖关系正确,不会出现注册丢失的情况。 - 明确的生命周期:把
IMapper也设为单例,因为它是线程安全的,重复使用更高效。
额外检查项
- 确认你的
MapperProfile类是正确实现的,比如:
public class MapperProfile : Profile { public MapperProfile() { // 在这里添加你的映射规则,比如: CreateMap<Request, RequestDto>(); } }
- 确保StructureMap容器初始化时正确加载了
InfrastructureRegistry,比如在WebApi的Global.asax中:
protected void Application_Start() { var container = new Container(new InfrastructureRegistry()); // 其他WebApi初始化代码... }
这样调整后,StructureMap就能正确解析IMapper并注入到RequestService中了。
内容的提问来源于stack exchange,提问作者klaydze
相关产品推荐
相关产品推荐

