您好,欢迎访问一九零五行业门户网

使用AutoMapper实现Dto和Model的自由转换(下)

书接上文。在上一篇文章中我们讨论了使用automapper实现类型间1-1映射的两种方式——convention和configuration,知道了如何进行简单的oo mapping。在这个系列的最后一篇文章我想基于我们的需求讨论一些中级别的话题,包括:如何实现类型体型之间的映射,以及如何为两个类型实现多个映射规则。 
【四】将一个类型映射为类型体系 
先回顾一下我们的dto和model。我们有bookdto,我们有author,每个author有自己的contactinfo。现在提一个问题:如何从bookdto得到第一个作者的author对象呢?答案即简单,又不简单。 
最简单的做法是,使用前面提到的countructusing,指定bookdto到author的全部字段及子类型字段的映射:
c#代码  
var map = mapper.createmap<bookdto,author>();  
map.constructusing(s => new author  
                            {  
                                name = s.firstauthorname,  
                                description = s.firstauthordescription,  
                                contactinfo = new contactinfo  
                                                  {  
                                                      blog = s.firstauthorblog,  
                                                      email = s.firstauthoremail,  
                                                      twitter = s.firstauthortwitter  
                                                  }  
                            });
这样的做法可以工作,但很不经济。因为我们是在从头做bookdto到author的映射,而从bookdto到contactinfo的映射是我们之前已经实现过的,实在没有必要重复再写一遍。设想一下,如果有一个别的什么reader类型里面也包含有contactinfo,在做bookdto到reader映射的时候,我们是不是再写一遍这个bookdto -> contactinfo逻辑呢?再设想一下如果我们在实现bookdto到book的映射的时候,是不是又需要把bookdto到author的映射规则再重复写一遍呢? 
所以我认为对于这种类型体系间的映射,比较理想的做法是为每个具体类型指定简单的映射,而后在映射复杂类型的时候再复用简单类型的映射。用简单点的语言描述: 
我们有a,b,c,d四个类型,其中b = [c, d]。已知a -> c, a -> d, 求a -> b。 
我的解法是使用automapper提供的——ivalueresolver。ivalueresolver是automapper为实现字段级别的特定映射逻辑而定义的类型,它的定义如下:
c#代码  
public interface ivalueresolver  
{  
    resolutionresult resolve(resolutionresult source);  
}
而在实际的应用中我们往往会使用它的泛型子类——valueresolver,并实现它的抽象方法:
c#代码  
protected abstract tdestination resolvecore(tsource source);
其中tsource为源类型,tdestination为目标字段的类型。 
回到我们的例子,我们现在可以这样来映射bookdto -> author:
c#代码  
var map = mapper.createmap<bookdto, author>();  
map.formember(d => d.name, opt => opt.mapfrom(s => s.firstauthorname))  
    .formember(d => d.description, opt => opt.mapfrom(s => s.firstauthordescription))  
    .formember(d => d.contactinfo,  
               opt => opt.resolveusing<firstauthorcontactinforesolver>()));
在firstauthorcontactinforesolver中我们实现valueresolver并复用bookdto -> contactinfo的逻辑:
c#代码  
public class firstauthorcontactinforesolver : valueresolver<bookdto,contactinfo>  
{  
    protected override contactinfo resolvecore(bookdto source)  
    {  
        return mapper.map<bookdto, contactinfo>(source);  
    }  
}
一切就搞定了。 
类似的,我们现在也可以实现bookdto -> book了吧?通过复用bookdto -> author以及bookdto -> publisher。 
真的可以吗?好像还有问题。是的,我们会发现需要从bookdto映射到两个不同的author,它们的字段映射规则是不同的。怎么办?赶紧进入我们的最后一个议题。 
【五】为两个类型实现多套映射规则 
我们的问题是:对于类型a和b,需要定义2个不同的a -> b,并让它们可以同时使用。事实上目前的automapper并没有提供现成的方式做到这一点。 
当然我们可以采用“曲线救国”的办法——为first author和second author分别定义author的两个子类,比如说firstauthor和secondauthor,然后分别实现bookdto -> firstauthor和bookdto -> secondauthor映射。但是这种方法也不太经济。假如还有第三作者甚至第四作者呢?为每一个作者都定义一个author的子类吗? 
另一方面,我们不妨假设一下,如果automapper提供了这样的功能,那会是什么样子呢?createmap方法和map方法应该这样定义:
c#代码  
createmap<tsource, tdestination>(string tag)  
map<tsource, tdestination>(tsource, string tag)
其中有一个额外的参数tag用于标识该映射的标签。 
而我们在使用的时候,就可以:
c#代码  
var firstauthormap = mapper.createmap<bookdto, author>(first);  
// define bookdto -> first author rule  
var secondauthormap = mapper.createmap<bookdto, author>(second);  
// define bookdto -> second author rule  
var firstauthor = mapper.map<bookdto, author>(source, first);  
var secondauthor = mapper.map<bookdto, author>(source, second);
遗憾的是,这一切都是假如。但是没有关系,虽然automapper关上了这扇门,却为我们留着另一扇门——mappingengine。 
mappingengine是automapper的映射执行引擎,事实上在mapper中有默认的mappingengine,我们在调用mapper.createmap的时候,是往与这个默认的mappingengine对应的configuration中写规则,在调用mapper.map获取对象的时候则是使用默认的mappingengine执行其对应configuration中的规则。 
简而言之一个mappingengine就是一个automapper的“虚拟机”,如果我们同时启动多个“虚拟机”,并且将针对同一对类型的不同映射规则放到不同的“虚拟机”上,就可以让它们各自相安无事的运行起来,使用的时候要用哪个规则就问相应的“虚拟机”去要好了。 
说做就做。首先我们定义一个mappingengineprovider类,用它来获取不同的mappingengine:
c#代码  
public class mappingengineprovider  
{  
    private readonly mappingengine _engine;
public mappingengine get()  
    {  
        return _engine;  
    }  
}
我们将不同类型的映射规则抽象为接口imapping:
c#代码  
public interface imapping  
{  
    void addto(configuration config);  
}
然后在mappingengineprovider的构造函数里将需要的规则放到对应的mappingengine中:
c#代码  
private static dictionary<engine,list<imapping>> _rules=new dictionary<engine, list<imapping>>();
public mappingengineprovider(engine engine)  
{  
    var config = new configuration(new typemapfactory(), mapperregistry.allmappers());  
    _rules[engine].foreach(r=> r.addto(config));  
    _mappingengine = new mappingengine(config);  
}
注意到这里我们用了一个枚举类型engine用于标识可能的mappingengine:
c#代码  
public enum engine  
{  
    basic = 0,  
    first,  
    second  
}
我们用到了3个engine,basic用于放置所有基本的映射规则,first用于放置所有dto -> firstxxx的规则,second则用于放置所有dto -> secondxxx的规则。 
我们还定义了一个放置所有映射规则的字典_rule,将规则分门别类放到不同的engine中。 
剩下的事情就是往字典_rule里填充我们的mapping了。比如说我们把bookdtotofirstauthormapping放到first engine里并把bookdtotosecondauthormapping放到second engine里:
c#代码  
private static readonly dictionary<engine, list<imapping>> _rules =  
    new dictionary<engine, list<imapping>>  
        {  
            {  
                engine.first, new list<imapping>  
                                  {  
                                      new bookdtotofirstauthormapping(),  
                                  }  
                },  
            {  
                engine.second, new list<imapping>  
                                   {  
                                       new bookdtotosecondauthormapping(),  
                                   }  
                },  
        };
当然为了方便使用我们可以事先实例化好不同的mappingengineprovider对象:
c#代码  
public static simplemappingengineprovider first = new mappingengineprovider(engine.first);  
public static simplemappingengineprovider second = new mappingengineprovider(engine.second);
现在我们就可以在映射bookdto -> book的时候同时使用这2个engine来得到2个author并把它们组装到字段book.authors里面了:
c#代码  
public class bookdtotobookmapping : defaultmapping<bookdto, book>  
{  
    protected override void mapmembers(imappingexpression<bookdto, book> map)  
    {  
        map.formember(d => d.authors,  
                       opt => opt.resolveusing<authorsvalueresolver>());  
    }
private class authorsvalueresolver : valueresolver<bookdto, list<author>>  
    {  
        protected override list<author> resolvecore(bookdto source)  
        {  
            var firstauthor = simplemappingengineprovider.first.get().map<bookdto, author>(source);  
            var secondauthor = simplemappingengineprovider.second.get().map<bookdto, author>(source);  
            return firstauthor.isnull()  
                       ? secondauthor.isnull() ? new list<author>() : new list<author> {new author(), secondauthor}  
                       : secondauthor.isnull()  
                             ? new list<author> {firstauthor}  
                             : new list<author> {firstauthor, secondauthor};  
        }  
    }
}
最后,还记得我们在本节开始的时候提到的美好愿望吗?既然automapper没有帮我们实现,就让我们自己来实现吧:
c#代码  
public class mymapper  
{  
    private static readonly dictionary<engine, mappingengine> engines = new dictionary<engine, mappingengine>  
                                                                   {  
                                                                       {engine.basic, mappingengineprovider.basic.get()},  
                                                                       {engine.first, mappingengineprovider.first.get()},  
                                                                       {engine.second, mappingengineprovider.second.get()},  
                                                                   };
public static ttarget map<tsource, ttarget>(tsource source, engine engine = engine.basic)  
    {  
        return engines[engine].map<tsource, ttarget>(source);  
    }  
}
一切又都回来了,我们可以这样:
c#代码  
var firstauthor = mymapper.map<bookdto,author>(dto, engine.first);  
var secondauthor = mymapper.map<bookdto,author>(dto, engine.second);
也可以这样了:
c#代码  
var book = mymapper.map<bookdto,book>(dto);
后记: 发现在家里要上传文件到github真是奇慢无比,所有我决定先把自己的代码打包上传,欢迎大家参考使用。
其它类似信息

推荐信息