使用Unity注册Automapper

3

我正在尝试将Automapper 3.2.1与Unity 3.0.1304.1注册。我已经尝试了StackOverflow上的常规注册答案,但都没有成功。你有什么线索可以正确地将最新版本的Automapper与Unity注册吗?在最近的版本中是否有任何更改?以下是代码和异常:


像这样注册:

container.RegisterType<ConfigurationStore, ConfigurationStore>(new ContainerControlledLifetimeManager(), new InjectionConstructor(typeof(ITypeMapFactory), MapperRegistry.Mappers));
container.RegisterType<IConfigurationProvider, ConfigurationStore>();
container.RegisterType<IConfiguration, ConfigurationStore>();
container.RegisterType<IMappingEngine, MappingEngine>();
container.RegisterType<ITypeMapFactory, TypeMapFactory>();

接着我收到了以下错误:

IDictionary`2 类型没有可访问的构造函数。


此时,正在解决这个问题:

  Resolving AutoMapper.MappingEngine,(none) (mapped from AutoMapper.IMappingEngine, (none))
  Resolving parameter "objectMapperCache" of constructor AutoMapper.MappingEngine(AutoMapper.IConfigurationProvider configurationProvider, AutoMapper.Internal.IDictionary`2[[AutoMapper.Impl.TypePair, AutoMapper, Version=3.2.1.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005],[AutoMapper.IObjectMapper, AutoMapper, Version=3.2.1.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005]] objectMapperCache, System.Func`2[[System.Type, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] serviceCtor)
    Resolving AutoMapper.Internal.IDictionary`2[AutoMapper.Impl.TypePair,AutoMapper.IObjectMapper],(none)

这就是为什么你真的不应该尝试注册属于第三方框架的公共类型。无论如何,有什么阻止你在AutoMapper上方提供一层抽象并进行注册呢? - George Howarth
我明白你的意思...我只是想让它能够工作,因为很多其他人在SO上说他们已经让它工作了。包装它没有问题,我想这就是我要走的路。感谢您的回复。 - user3779599
1个回答

2

尝试在IMappingEngine注册中使用InjectionConstructor,示例如下:

container.RegisterType<IMappingEngine, MappingEngine>(new InjectionConstructor(typeof(IConfigurationProvider)));

谢谢,我可能会在某个时候尝试这个...我最终在映射引擎上放置了一个适配器,以便进行模拟。 - user3779599
你收到这样的异常的原因是Unity尝试使用具有最大参数(在你的情况下为2)的构造函数来解析类型。通过使用InjectionConstructor,您可以指示Unity改用特定的构造函数。 - Sat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接