我的某些SharePoint库存在一个问题。我想映射一下我的模型'反对' ListItem'宾语。很遗憾,' ListItem'对象没有任何构造函数,我需要使用SharePoint库中的函数对其进行初始化。是否有可能(在映射之前)给出映射对象的实例?
public void AddToList(Model model)
{
// 'new ListItem()' is fobbiden. 'CreateListItemInstance()'
// creates 'instance' using client context, list name which aren't
// inside 'model' object.
ListItem instance = this.CreateListItemInstance();
// (Model -> ListItem) It throws exception, because automapper
// try to create instance of ListItem.
ListItem parsedItem = Mapper.Map<ListItem>(model);
// I would like to have something like below:
// Mapper.Map<ListItem>(model).UseInstance(instance);
this.SharePointListItemRepository.Insert(parsedItem);
this.SharePointListItemRepository.Save();
}
更新(12/22/2017)
我使用ResolutionContext将实例传递给mapper,我在ConstructUsing方法中使用此实例将构造函数替换为实例。
ListItem instance = this.CreateListItemInstance();
ListItem parsed = mapper.Map<ListItem>(model, opts =>
opts.Items["instance"] = instance); //passing instance to ResolutioContext
this.SharePointListItemRepository.Insert(parsed);
this.Save();
内部地图资料:
CreateMap<Model, ListItem>()
//Using 'ConstructUsing' method to use instance of Model
//(from resolutionContext) as constructor.
.ConstructUsing((source, resolutionContext) =>
(resolutionContext.Items["instance"] as ListItem))
//Mappings...
.AfterMap((source, destination) =>
{
destination["Title"] = source.Title;
});
答案 0 :(得分:0)
结帐this article:
因为我们只向AutoMapper提供了自定义解析器的类型,所以映射引擎将使用反射来创建值解析器的实例。
如果我们不希望AutoMapper使用反射来创建实例,我们可以直接提供它:
Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.Total, opt => opt.ResolveUsing(new CustomResolver()) );
取代
opt.ResolveUsing(new CustomResolver())
可能有:
opt.ResolveUsing(CreateListItemInstance())