将创建的对象实例传递给映射器

问题描述 投票:0回答:1

我有一些SharePoint库的问题。我想将我的'Model'对象映射到'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;
            });
c# sharepoint mapping automapper repository-pattern
1个回答
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())
© www.soinside.com 2019 - 2024. All rights reserved.