You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.9 KiB
59 lines
1.9 KiB
using AutoMapper;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace QYMessageCenter.Common.Extensions
|
|
{
|
|
public static class MapperExtension
|
|
{
|
|
private static IMapper _mapper;
|
|
|
|
/// <summary>
|
|
/// 注册对象映射器
|
|
/// </summary>
|
|
/// <param name="services"></param>
|
|
/// <param name="profile"></param>
|
|
/// <returns></returns>
|
|
public static IServiceCollection AddMapper(this IServiceCollection services, Profile profile)
|
|
{
|
|
var config = new MapperConfiguration(cfg =>
|
|
{
|
|
cfg.AddProfile(profile);
|
|
});
|
|
_mapper = config.CreateMapper();
|
|
return services;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 设置对象映射执行者
|
|
/// </summary>
|
|
/// <param name="mapper">映射执行者</param>
|
|
public static void SetMapper(IMapper mapper)
|
|
{
|
|
_mapper = mapper;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将对象映射为指定类型
|
|
/// </summary>
|
|
/// <typeparam name="TTarget">要映射的目标类型</typeparam>
|
|
/// <param name="source">源对象</param>
|
|
/// <returns>目标类型的对象</returns>
|
|
public static TTarget Map<TTarget>(this object source)
|
|
{
|
|
return _mapper.Map<TTarget>(source);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 使用源类型的对象更新目标类型的对象
|
|
/// </summary>
|
|
/// <typeparam name="TSource">源类型</typeparam>
|
|
/// <typeparam name="TTarget">目标类型</typeparam>
|
|
/// <param name="source">源对象</param>
|
|
/// <param name="target">待更新的目标对象</param>
|
|
/// <returns>更新后的目标类型对象</returns>
|
|
public static TTarget Map<TSource, TTarget>(this TSource source, TTarget target)
|
|
{
|
|
return _mapper.Map(source, target);
|
|
}
|
|
}
|
|
}
|
|
|