网站首页 网站源码

using System;
using System.Reflection;
using AutoMapper;
namespace Dpz.Core.Infrastructure.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]);
}
}
上述代码定义了一组用于自动映射的特性(Attributes),主要用于配置对象之间的映射规则,使用了 AutoMapper 库。以下是代码的详细解释:
AutoMappingAttribute 抽象基类SourceType: 源类型,表示要映射的源对象的类型。DestinationType: 目标类型,表示映射后目标对象的类型。ConfigureMapping: 抽象方法,子类需要实现该方法以配置映射规则。AutoMapAttribute 类ReverseMap: 布尔值,指示是否需要创建反向映射,默认为 true。ConfigureMapping: 实现了基类的方法,使用 AutoMapper 的 CreateMap 方法创建源类型和目标类型之间的映射。如果 ReverseMap 为 true,则还会创建反向映射。CustomMapAttribute 类ConfigurationMethod: 字符串,表示要调用的静态配置方法的名称。ConfigureMapping: 实现了基类的方法,通过反射查找并调用指定的静态方法来配置映射。该方法需要接受一个 MapperConfigurationExpression 类型的参数。这段代码的主要目的是提供一种灵活的方式来定义对象之间的映射规则。通过使用特性,开发者可以在类上标记需要映射的源类型和目标类型,并通过 AutoMapper 库自动生成映射配置。AutoMapAttribute 提供了简单的双向映射,而 CustomMapAttribute 则允许开发者自定义映射逻辑。这样的设计使得代码更加清晰和可维护。
