知道如何告诉AutoMapper使用StructureMap解析TypeConverter构造函数参数吗?
即。我们有这个:
private class StringIdToContentProviderConverter : TypeConverter<string, ContentProvider> {
private readonly IContentProviderRepository _repository;
public StringIdToContentProviderConverter(IContentProviderRepository repository) {
_repository = repository;
}
public StringIdToContentProviderConverter() {
_repository = ObjectFactory.GetInstance<IContentProviderRepository>();
}
protected override ContentProvider ConvertCore(string contentProviderId) {
return _repository.Get(new Guid(contentProviderId));
}
}
在AutoMap注册中:
Mapper.CreateMap<Guid, ContentProvider>().ConvertUsing<GuidToContentProviderConverter>();
但是,我不喜欢在转换器的构造函数中硬连接ObjectFactory.GetInstance的想法。如何告诉AutoMapper如何解析我的IContentProviderRepository?
或者使用Automapper使用存储库从viewmodel ID水合域对象的其他方法的想法?
答案 0 :(得分:4)
我们使用它(在我们的一个Bootstrapper任务中)......
private IContainer _container; //Structuremap container
Mapper.Initialize(map =>
{
map.ConstructServicesUsing(_container.GetInstance);
map.AddProfile<MyMapperProfile>();
}
答案 1 :(得分:1)
ConstructUsing
方法似乎有一个接受Func<T1,T2>
的重载。在那里你可以访问你的容器。
修改强> 转换也知道这样的过载,你可以这样做:
Mapper.CreateMap<A, B>().ConvertUsing(i=> c.With(i).GetInstance<B>());
其中c是你的容器