欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

(28)ASP.NET Core AutoMapper组件

程序员文章站 2022-05-28 23:07:23
1.什么是AutoMapper? AutoMapper是一个对象-对象映射器。对象-对象映射通过将一种类型的输入对象转换为另一种类型的输出对象来工作。使AutoMapper变得有趣的是,它提供了一些有趣的约定,免去用户不需要了解如何将类型A映射为类型B。只要类型B遵循AutoMapper既定的约定, ......

1.什么是automapper?

automapper是一个对象-对象映射器。对象-对象映射通过将一种类型的输入对象转换为另一种类型的输出对象来工作。使automapper变得有趣的是,它提供了一些有趣的约定,免去用户不需要了解如何将类型a映射为类型b。只要类型b遵循automapper既定的约定,就需要几乎零配置来映射两个类型。映射代码虽然比较无聊,但是automapper为我们提供简单的类型配置以及简单的映射测试,而映射可以在应用程序中的许多地方发生,但主要发生在层之间的边界中,比如,ui /域层之间或服务/域层之间。一层的关注点通常与另一层的关注点冲突,因此对象-对象映射导致分离的模型,其中每一层的关注点仅会影响该层中的类型。

2.如何在core上面使用automapper组件?

先在startup.configureservices注入automapper组件服务,然后在startup.configure上获取automapper服务配置扩展类创建对象-对象映射关系,为了好统一管理代码,可以新建一个automapperextension静态类,把以下代码封装一下:

public static class automapperextension
{
    /// <summary>
    /// 新增自动映射服务
    /// </summary>
    /// <param name="service"></param>
    /// <returns></returns>
    public static iservicecollection addautomapper(this iservicecollection services)
    {
        #region 方案一
        //注册automapper配置扩展类服务
        services.tryaddsingleton<mapperconfigurationexpression>();
        //注册automapper配置扩展类到automapper配置服务去
        services.tryaddsingleton(serviceprovider =>
        {
            var mapperconfigurationexpression = serviceprovider.getrequiredservice<mapperconfigurationexpression>();
            var mapperconfiguration = new mapperconfiguration(mapperconfigurationexpression);
            mapperconfiguration.assertconfigurationisvalid();
            return mapperconfiguration;
        });
        //注入imapper接口di服务
        services.tryaddsingleton(serviceprovider =>
        {
            var mapperconfiguration = serviceprovider.getrequiredservice<mapperconfiguration>();
            return mapperconfiguration.createmapper();
        });
        return services;
        #endregion
    }

    /// <summary>
    /// 使用自动映射配置扩展类
    /// </summary>
    /// <param name="applicationbuilder"></param>
    /// <returns></returns>
    public static imapperconfigurationexpression useautomapper(this iapplicationbuilder applicationbuilder)
    {
        //获取已注册服务automapper配置扩展类
        return applicationbuilder.applicationservices.getrequiredservice<mapperconfigurationexpression>();
    }
}
// this method gets called by the runtime. use this method to add services to the container.
public void configureservices(iservicecollection services)
{
    ......
    //添加自动映射组件di服务
    services.addautomapper();
}
// this method gets called by the runtime. use this method to configure the http request pipeline.
public void configure(iapplicationbuilder app, ihostingenvironment env)
{
    ......
    //注册组件之后,创建映射对象
  var expression = app.useautomapper();
    expression.createmap<customer, customerdto>();
    expression.createmap<address, addressdto>();
}

因为imapper接口已经在configureservices方法注入di服务了,所以无需再重新注入,只需要直接使用imapper调用其方法就可以:

public class blogscontroller : controller
{
    private imapper _imapper { get; }
    public blogscontroller(imapper imapper)
    {
        _imapper = imapper;
    }
    // get: blogs
    public async task<iactionresult> index()
    {
    //对象-对象数据传输
        var dto = _imapper.map<customerdto>(customerinitialize());
        ......
    }
    //手动赋值客户对象数据
    private customer customerinitialize()
    {
        var _customer = new customer()
        {
            id = 1,
            name = "eduardo najera",
            credit = 234.7m,
            address = new address() { city = "istanbul", country = "turkey", id = 1, street = "istiklal cad." },
            homeaddress = new address() { city = "istanbul", country = "turkey", id = 2, street = "istiklal cad." },
            workaddresses = new list<address>()
            {
                new address() {city = "istanbul", country = "turkey", id = 5, street = "istiklal cad."},
                new address() {city = "izmir", country = "turkey", id = 6, street = "konak"}
            },
            addresses = new list<address>()
            {
                new address() {city = "istanbul", country = "turkey", id = 3, street = "istiklal cad."},
                new address() {city = "izmir", country = "turkey", id = 4, street = "konak"}
            }.toarray()
        };
        return _customer;
    }
}

运行效果:

(28)ASP.NET Core AutoMapper组件

3.如果更加灵活使用automapper组件?

相信在第二章节时候,相信大家都会发现一个问题,如果生产场景业务越来越庞大,需创建对应业务对象也会越来越多,如果面对这样的业务场景难道要在configure方法里面创建越来越多的映射关系吗?例:

var expression = app.useautomapper();
expression.createmap<a, adto>();
expression.createmap<b, bdto>();
expression.createmap<c, cdto>();
expression.createmap<d, ddto>();
......

很显然这样子是不可行的,这样会导致后续代码越来越多,难以维护。那么现在让我们来解决这个问题。首先新建一个自动注入属性的autoinjectattribute密封类,具体代码如下:

public sealed class autoinjectattribute : attribute
{
    public type sourcetype { get; }
    public type targettype { get; }
    public autoinjectattribute(type sourcetype, type targettype)
    {
        sourcetype = sourcetype;
        targettype = targettype;
    }
}

新增这个autoinjectattribute密封类,目的是声明每个dto对象(数据传输对象)与对应数据源对象是传输关系,方便在configure里面自动注册创建映射关系,例:

//声明源对象,目标对象
[autoinject(sourcetype: typeof(customer),targettype:typeof(customerdto))]
public class customerdto
{
    public int id { get; set; }
    public string name { get; set; }
    public address address { get; set; }
    public addressdto homeaddress { get; set; }
    public addressdto[] addresses { get; set; }
    public list<addressdto> workaddresses { get; set; }
    public string addresscity { get; set; }
}

然后创建一个自动注入autoinjectfactory工厂类,检测运行中的程序集是否有autoinjectattribute属性声明,如果有则插入一个类型数据集中返回,目的是把所有声明需要映射dto对象跟数据源对象自动创建映射关系:

public class autoinjectfactory
{
    public list<(type, type)> addassemblys
    {
        get
        {
            var assemblys =new list<assembly>() { assembly.getexecutingassembly() };
            list<(type, type)> convertlist = new list<(type, type)>();
            foreach (var assembly in assemblys)
            {
                var atributes = assembly.gettypes()
                    .where(_type => _type.getcustomattribute<autoinjectattribute>() != null)
                    .select(_type => _type.getcustomattribute<autoinjectattribute>());
                foreach (var atribute in atributes)
                {
                    convertlist.add((atribute.sourcetype, atribute.targettype));
                }
            }
            return convertlist;
        }
    }
}

在第2小节automapperextension静态类的addautomapper方法内修改如下代码:

#region 方案二
//注入automapper配置扩展类服务
services.tryaddsingleton<mapperconfigurationexpression>();
//注入自动注入工厂类服务
services.tryaddsingleton<autoinjectfactory>();
//注入automapper配置扩展类到automapper配置服务去
services.tryaddsingleton(serviceprovider =>
{
    var mapperconfigurationexpression = serviceprovider.getrequiredservice<mapperconfigurationexpression>();
    //通过自动注入工厂类获取声明数据源对象与dto对象自动创建映射关系
    var factory = serviceprovider.getrequiredservice<autoinjectfactory>();
    foreach (var (sourcetype, targettype) in factory.addassemblys)
    {
        mapperconfigurationexpression.createmap(sourcetype, targettype);
    }
    var mapperconfiguration = new mapperconfiguration(mapperconfigurationexpression);
    mapperconfiguration.assertconfigurationisvalid();
    return mapperconfiguration;
});
//注入imapper接口di服务
services.tryaddsingleton(serviceprovider =>
{
    var mapperconfiguration = serviceprovider.getrequiredservice<mapperconfiguration>();
    return mapperconfiguration.createmapper();
});
return services;
#endregion

再新增一个使用自动注入工厂类服务静态方法:

/// <summary>
/// 使用自动注入工厂类
/// </summary>
/// <param name="applicationbuilder"></param>
public static void useautoinject(this iapplicationbuilder applicationbuilder)
{
   applicationbuilder.applicationservices.getrequiredservice<autoinjectfactory>();
}

然后在startup.configureservices注入automapper组件服务,然后在startup.configure上调用useautoinject静态方法,具体代码如下:

app.useautoinject();

运行效果:
(28)ASP.NET Core AutoMapper组件
从运行结果来看依然是这个酸爽!

参考文献:
automapper