上次我们讲了如何在.Net Core下使用AutoMapper,我们采用的是AutoMapper 9.0。上次的方法如下
var dto = _mapper.Map<sys_user, sys_userDto>(q);//_mapper.Map<sys_userDto>(q);
这样也能用,但这样代码好像麻烦了点,我们现在可以自己定义一个AutoMapperHelper方法让调用变得方便一点。
using AutoMapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace MyUtility.AutoMapper {
public static class AutoMapperHelper {
private static IServiceProvider ServiceProvider;
public static void UseStateAutoMapper(this IApplicationBuilder applicationBuilder) {
ServiceProvider = applicationBuilder.ApplicationServices;
}
public static TDestination Map<TDestination>(object source) {
var mapper = ServiceProvider.GetRequiredService<IMapper>();
return mapper.Map<TDestination>(source);
}
public static TDestination Map<TSource, TDestination>(TSource source) {
var mapper = ServiceProvider.GetRequiredService<IMapper>();
return mapper.Map<TSource, TDestination>(source);
}
public static TDestination MapTo<TSource, TDestination>(this TSource source) {
var mapper = ServiceProvider.GetRequiredService<IMapper>();
return mapper.Map<TSource, TDestination>(source);
}
public static TDestination MapTo<TDestination>(this object source) {
var mapper = ServiceProvider.GetRequiredService<IMapper>();
return mapper.Map<TDestination>(source);
}
public static List<TDestination> MapToList<TDestination>(this IEnumerable source) {
var mapper = ServiceProvider.GetRequiredService<IMapper>();
return mapper.Map<List<TDestination>>(source);
}
public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source) {
var mapper = ServiceProvider.GetRequiredService<IMapper>();
return mapper.Map<List<TDestination>>(source);
}
}
}
然后在Startup文件中Configure方法里注册下
//AutoMapperHelper扩展方法注册
app.UseStateAutoMapper();
这样调用方法就可以改成,直接实现了一个扩展方法
var dto = q.MapTo<sys_userDto>();
相对来说更简洁点了
注意,这里重点是要明白IServiceProvider接口,IServiceProvider可以根据IApplicationBuilder来提供,在Startup文件中的Configure方法会注入IApplicationBuilder,那么我们自定义的AutoMapperHelper扩展方法就可以对IApplicationBuilder扩展来获得IServiceProvider,
IServiceProvider说明
在ASP.NET Core的容器中,系统提供了IServiceCollection来注册服务和提供了IServiceProvider这个让我们解析各种注册过的服务,提供GetService()和GetRequiredService()两个方法来解析服务。可以参考下一下文章了解下这个知识点
ASP.NET Core中GetService()和GetRequiredService()之间的区别
那么我们就可以通过IServiceProvider来解析IMapper,从而来实现映射处理。