using AutoMapper;
using Microsoft.Extensions.DependencyInjection;
namespace SiNan.Common.Extensions
{
public static class MapperExtension
{
private static IMapper _mapper;
///
/// 注册对象映射器
///
///
///
///
public static IServiceCollection AddMapper(this IServiceCollection services, Profile profile)
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(profile);
});
_mapper = config.CreateMapper();
return services;
}
///
/// 设置对象映射执行者
///
/// 映射执行者
public static void SetMapper(IMapper mapper)
{
_mapper = mapper;
}
///
/// 将对象映射为指定类型
///
/// 要映射的目标类型
/// 源对象
/// 目标类型的对象
public static TTarget Map(this object source)
{
return _mapper.Map(source);
}
///
/// 使用源类型的对象更新目标类型的对象
///
/// 源类型
/// 目标类型
/// 源对象
/// 待更新的目标对象
/// 更新后的目标类型对象
public static TTarget Map(this TSource source, TTarget target)
{
return _mapper.Map(source, target);
}
}
}