![](/img/trans.png)
[英]Error activating IConfigurationProvider when using AutoMapper
[英]AutoMapper Unity AutoMapper.IConfigurationProvider Issue
我正在嘗試將我的AutoMapper(版本5.2.0)Profile類注冊到我的Unity容器(Unity版本4.0.1)中,這給了我一個例外:
依賴關系的解析失敗,類型= IConsumer`1 [Commands.INewUserEmailCommand]“,名稱=”(none)“。發生異常,而:正在解析。異常是: InvalidOperationException-當前類型AutoMapper.IConfigurationProvider是接口,並且無法構造。是否缺少類型映射?
這是配置文件類:
public class AutoMapperBootstrap : Profile
{
public AutoMapperBootstrap()
{
this.CreateMap<IUserEmailDTO, MergeUserEmailRequest>();
}
}
這是Unity注冊代碼段:
Profile typeMaps = new AutoMapperBootstrap();
var config = new MapperConfiguration(cfg => cfg.AddProfile(typeMaps));
container.RegisterInstance<IMapper>(config.CreateMapper(), new ContainerControlledLifetimeManager());
然后,我有依賴於注入的IMapper實例的構造函數,顯然Unity對此一無所知,還是需要一些額外的IConfigurationProvider實例? 我想念什么? 當我的代碼需要調用依賴IMapper的服務時,Unity會拋出上述異常。 這是使用構造函數注入嘗試獲取IMapper實例的服務的示例。
public class FooService : IFooService
{
private readonly IMapper mapper;
public Foo(IMapper mapper)
{
this.mapper = mapper;
}
}
@Andy,我想您只是在映射上復制了部分錯誤,通常automapper會為您提供更多錯誤詳細信息,並為您提供線索。
在下面的行中,您嘗試注冊IMapper類的實例
container.RegisterInstance<IMapper>(config.CreateMapper(), new ContainerControlledLifetimeManager());
如果您查看CreateMapper的實際工作方式,會發現它使用了IConfigurationProvider,請查看下面的automapper原始代碼
public class MapperConfiguration : IConfigurationProvider
{
.....
public IMapper CreateMapper()
{
return (IMapper) new Mapper((IConfigurationProvider) this);
}
.....
}
當automapper嘗試創建Mapper
的實例時,也嘗試解析參數IConfigurationProvider
。 在這種情況下,您永遠不會注入該參數。 解決方案:注入該參數的實例,僅此而已
在這里,我將為您保存一個有關如何使用它的示例
class Helper
{
public static MapperConfiguration InitializeAutoMapper()
{
MapperConfiguration config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new ProfileA());
cfg.AddProfile(new ProfileB());
});
return config;
}
}
在您的Unity上注冊,其中container
是IUnityContainer
的實例
var mapperConfig = Helper.InitializeAutoMapper();
var mapper = mapperConfig.CreateMapper();
container.RegisterType<IMapper, Mapper>(new InjectionConstructor(mapperConfig));
container.RegisterInstance(mapper, Activator.CreateInstance<T>());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.