using System.Reflection;
using AutoMapper;
namespace Dpz.Core.Entity.Base.MapperConfig;
/// <summary>
/// 自动映射特性基类
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public abstract class AutoMappingAttribute(Type sourceType, Type destinationType) : Attribute
{
public Type SourceType { get; } = sourceType;
public Type DestinationType { get; } = destinationType;
/// <summary>
/// 配置映射规则
/// </summary>
public abstract void ConfigureMapping(MapperConfigurationExpression cfg);
}
/// <summary>
/// 简单双向映射特性
/// </summary>
public class AutoMapAttribute(Type sourceType, Type destinationType)
: AutoMappingAttribute(sourceType, destinationType)
{
public bool ReverseMap { get; set; } = true;
public override void ConfigureMapping(MapperConfigurationExpression cfg)
{
var map = cfg.CreateMap(SourceType, DestinationType);
if (ReverseMap)
{
map.ReverseMap();
}
}
}
/// <summary>
/// 自定义映射特性
/// </summary>
public class CustomMapAttribute(Type sourceType, Type destinationType, string configurationMethod)
: AutoMappingAttribute(sourceType, destinationType)
{
public string ConfigurationMethod { get; } = configurationMethod;
public override void ConfigureMapping(MapperConfigurationExpression cfg)
{
// 通过反射调用指定的静态配置方法
var method = DestinationType.GetMethod(
ConfigurationMethod,
BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,
null,
[typeof(MapperConfigurationExpression)],
null
);
method?.Invoke(null, [cfg]);
}
}
⚠⚠ 以下内容为AI分析的结果,请根据实际情况进行判断。
AutoMapper 配置特性解析
这段代码定义了一个基于特性的 AutoMapper 配置系统,允许开发者通过特性(Attribute)来声明类型之间的映射关系。以下是详细解释:
核心结构
1. AutoMappingAttribute 基类
- 这是一个抽象基类,用于所有映射特性的基础
- 构造函数接受源类型(
sourceType)和目标类型(destinationType) - 定义了抽象方法
ConfigureMapping,子类必须实现以提供具体的映射配置
2. AutoMapAttribute 类
- 继承自
AutoMappingAttribute - 提供简单的双向映射功能
ReverseMap属性控制是否创建反向映射(默认为 true)- 实现
ConfigureMapping方法,使用 AutoMapper 的CreateMap和ReverseMap方法
3. CustomMapAttribute 类
- 继承自
AutoMappingAttribute - 允许通过指定静态方法名来自定义映射配置
- 构造函数额外接受一个
configurationMethod参数 - 实现
ConfigureMapping方法时,会通过反射调用指定的静态配置方法
功能特点
- 声明式映射配置:通过特性而非代码集中配置来定义映射关系
- 灵活性:
- 简单映射可使用
AutoMapAttribute - 复杂映射可使用
CustomMapAttribute引用自定义配置方法
- 简单映射可使用
- 双向映射支持:通过
ReverseMap属性轻松控制 - 可扩展性:可以创建更多继承自
AutoMappingAttribute的特性类
使用示例
// 简单双向映射
[AutoMap(typeof(Source), typeof(Destination))]
public class Destination { }
// 自定义映射
[CustomMap(typeof(Source), typeof(Destination), "ConfigureMapping")]
public class Destination
{
public static void ConfigureMapping(MapperConfigurationExpression cfg)
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"));
}
}
这种设计使得映射配置更加直观且与模型类紧密关联,提高了代码的可维护性。
评论加载中...