最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

ASP.NET?Core使用AutoMapper組件

 更新時(shí)間:2022年04月08日 10:30:38   作者:暗斷腸  
這篇文章介紹了ASP.NET?Core使用AutoMapper組件的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

1.什么是AutoMapper?

AutoMapper是一個(gè)對(duì)象-對(duì)象映射器。對(duì)象-對(duì)象映射通過(guò)將一種類型的輸入對(duì)象轉(zhuǎn)換為另一種類型的輸出對(duì)象來(lái)工作。使AutoMapper變得有趣的是,它提供了一些有趣的約定,免去用戶不需要了解如何將類型A映射為類型B。只要類型B遵循AutoMapper既定的約定,就需要幾乎零配置來(lái)映射兩個(gè)類型。映射代碼雖然比較無(wú)聊,但是AutoMapper為我們提供簡(jiǎn)單的類型配置以及簡(jiǎn)單的映射測(cè)試,而映射可以在應(yīng)用程序中的許多地方發(fā)生,但主要發(fā)生在層之間的邊界中,比如,UI /域?qū)又g或服務(wù)/域?qū)又g。一層的關(guān)注點(diǎn)通常與另一層的關(guān)注點(diǎn)沖突,因此對(duì)象-對(duì)象映射導(dǎo)致分離的模型,其中每一層的關(guān)注點(diǎn)僅會(huì)影響該層中的類型。

2.如何在Core上面使用AutoMapper組件?

先在Startup.ConfigureServices注入AutoMapper組件服務(wù),然后在Startup.Configure上獲取AutoMapper服務(wù)配置擴(kuò)展類創(chuàng)建對(duì)象-對(duì)象映射關(guān)系,為了好統(tǒng)一管理代碼,可以新建一個(gè)AutoMapperExtension靜態(tài)類,把以下代碼封裝一下:

public static class AutoMapperExtension
{
    /// <summary>
    /// 新增自動(dòng)映射服務(wù)
    /// </summary>
    /// <param name="service"></param>
    /// <returns></returns>
    public static IServiceCollection AddAutoMapper(this IServiceCollection services)
    {
        #region 方案一
        //注冊(cè)AutoMapper配置擴(kuò)展類服務(wù)
        services.TryAddSingleton<MapperConfigurationExpression>();
        //注冊(cè)AutoMapper配置擴(kuò)展類到AutoMapper配置服務(wù)去
        services.TryAddSingleton(serviceProvider =>
        {
            var mapperConfigurationExpression = serviceProvider.GetRequiredService<MapperConfigurationExpression>();
            var mapperConfiguration = new MapperConfiguration(mapperConfigurationExpression);
            mapperConfiguration.AssertConfigurationIsValid();
            return mapperConfiguration;
        });
        //注入IMapper接口DI服務(wù)
        services.TryAddSingleton(serviceProvider =>
        {
            var mapperConfiguration = serviceProvider.GetRequiredService<MapperConfiguration>();
            return mapperConfiguration.CreateMapper();
        });
        return services;
        #endregion
    }

    /// <summary>
    /// 使用自動(dòng)映射配置擴(kuò)展類
    /// </summary>
    /// <param name="applicationBuilder"></param>
    /// <returns></returns>
    public static IMapperConfigurationExpression UseAutoMapper(this IApplicationBuilder applicationBuilder)
    {
        //獲取已注冊(cè)服務(wù)AutoMapper配置擴(kuò)展類
        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)
{
    ......
    //添加自動(dòng)映射組件DI服務(wù)
    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)
{
    ......
    //注冊(cè)組件之后,創(chuàng)建映射對(duì)象
  var expression = app.UseAutoMapper();
    expression.CreateMap<Customer, CustomerDto>();
    expression.CreateMap<Address, AddressDto>();
}

因?yàn)镮Mapper接口已經(jīng)在ConfigureServices方法注入DI服務(wù)了,所以無(wú)需再重新注入,只需要直接使用IMapper調(diào)用其方法就可以:

public class BlogsController : Controller
{
    private IMapper _iMapper { get; }
    public BlogsController(IMapper iMapper)
    {
        _iMapper = iMapper;
    }
    // GET: Blogs
    public async Task<IActionResult> Index()
    {
    //對(duì)象-對(duì)象數(shù)據(jù)傳輸
        var dto = _iMapper.Map<CustomerDto>(CustomerInitialize());
        ......
    }
    //手動(dòng)賦值客戶對(duì)象數(shù)據(jù)
    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;
    }
}

運(yùn)行效果:

3.如果更加靈活使用AutoMapper組件?

相信在第二章節(jié)時(shí)候,相信大家都會(huì)發(fā)現(xiàn)一個(gè)問(wèn)題,如果生產(chǎn)場(chǎng)景業(yè)務(wù)越來(lái)越龐大,需創(chuàng)建對(duì)應(yīng)業(yè)務(wù)對(duì)象也會(huì)越來(lái)越多,如果面對(duì)這樣的業(yè)務(wù)場(chǎng)景難道要在Configure方法里面創(chuàng)建越來(lái)越多的映射關(guān)系嗎?例:

var expression = app.UseAutoMapper();
expression.CreateMap<A, ADto>();
expression.CreateMap<B, BDto>();
expression.CreateMap<C, CDto>();
expression.CreateMap<D, DDto>();
......

很顯然這樣子是不可行的,這樣會(huì)導(dǎo)致后續(xù)代碼越來(lái)越多,難以維護(hù)。那么現(xiàn)在讓我們來(lái)解決這個(gè)問(wèn)題。首先新建一個(gè)自動(dòng)注入屬性的AutoInjectAttribute密封類,具體代碼如下:

public sealed class AutoInjectAttribute : Attribute
{
    public Type SourceType { get; }
    public Type TargetType { get; }
    public AutoInjectAttribute(Type sourceType, Type targetType)
    {
        SourceType = sourceType;
        TargetType = targetType;
    }
}

新增這個(gè)AutoInjectAttribute密封類,目的是聲明每個(gè)DTO對(duì)象(數(shù)據(jù)傳輸對(duì)象)與對(duì)應(yīng)數(shù)據(jù)源對(duì)象是傳輸關(guān)系,方便在Configure里面自動(dòng)注冊(cè)創(chuàng)建映射關(guān)系,例:

//聲明源對(duì)象,目標(biāo)對(duì)象
[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; }
}

然后創(chuàng)建一個(gè)自動(dòng)注入AutoInjectFactory工廠類,檢測(cè)運(yùn)行中的程序集是否有AutoInjectAttribute屬性聲明,如果有則插入一個(gè)類型數(shù)據(jù)集中返回,目的是把所有聲明需要映射DTO對(duì)象跟數(shù)據(jù)源對(duì)象自動(dòng)創(chuàng)建映射關(guān)系:

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小節(jié)AutoMapperExtension靜態(tài)類的AddAutoMapper方法內(nèi)修改如下代碼:

#region 方案二
//注入AutoMapper配置擴(kuò)展類服務(wù)
services.TryAddSingleton<MapperConfigurationExpression>();
//注入自動(dòng)注入工廠類服務(wù)
services.TryAddSingleton<AutoInjectFactory>();
//注入AutoMapper配置擴(kuò)展類到AutoMapper配置服務(wù)去
services.TryAddSingleton(serviceProvider =>
{
    var mapperConfigurationExpression = serviceProvider.GetRequiredService<MapperConfigurationExpression>();
    //通過(guò)自動(dòng)注入工廠類獲取聲明數(shù)據(jù)源對(duì)象與DTO對(duì)象自動(dòng)創(chuàng)建映射關(guān)系
    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服務(wù)
services.TryAddSingleton(serviceProvider =>
{
    var mapperConfiguration = serviceProvider.GetRequiredService<MapperConfiguration>();
    return mapperConfiguration.CreateMapper();
});
return services;
#endregion

再新增一個(gè)使用自動(dòng)注入工廠類服務(wù)靜態(tài)方法:

/// <summary>
/// 使用自動(dòng)注入工廠類
/// </summary>
/// <param name="applicationBuilder"></param>
public static void UseAutoInject(this IApplicationBuilder applicationBuilder)
{
   applicationBuilder.ApplicationServices.GetRequiredService<AutoInjectFactory>();
}

然后在Startup.ConfigureServices注入AutoMapper組件服務(wù),然后在Startup.Configure上調(diào)用UseAutoInject靜態(tài)方法,具體代碼如下:

app.UseAutoInject();

運(yùn)行效果:

到此這篇關(guān)于ASP.NET Core使用AutoMapper組件的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

枣强县| 张家界市| 富阳市| 腾冲县| 汝南县| 荥阳市| 阜新市| 灵台县| 佛山市| 托里县| 阿坝县| 区。| 驻马店市| 讷河市| 福建省| 金阳县| 镇远县| 南雄市| 宁武县| 滦平县| 财经| 汶川县| 潜江市| 武宁县| 新化县| 海宁市| 神木县| 漠河县| 汪清县| 宜城市| 无棣县| 普格县| 乳源| 浦东新区| 临颍县| 锦州市| 科技| 寿光市| 平昌县| 白水县| 瑞金市|