You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSLA能否批量为特定类型属性添加BusinessRule免手动逐个配置?

全局DateTime属性校验规则自动注册实现方案

你当前逐属性手动添加规则的重复工作,可以通过反射扫描+基类统一注册的方式完全消除,不需要在每个业务类中重复编写规则添加代码。

核心实现逻辑

所有需要应用业务规则的实体统一继承通用业务基类,在基类的规则初始化阶段,通过反射自动扫描当前类下所有DateTime类型的属性元数据,批量注册DateValidRule校验规则。

步骤1:在业务基类中实现自动扫描注册

以下代码适配你当前使用的规则编写范式(从BusinessRules、IPropertyInfo的写法判断,兼容CSLA类框架的规则体系):

public abstract class BusinessBase
{
    protected virtual void InitializeBusinessRules()
    {
        // 扫描当前类所有公共静态的DateTime/可空DateTime类型属性元数据
        var dateTypeProps = GetType()
            .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
            .Where(field => field.FieldType == typeof(IPropertyInfo<DateTime>) 
                            || field.FieldType == typeof(IPropertyInfo<DateTime?>))
            .Select(field => field.GetValue(this) as IPropertyInfo)
            .ToList();

        // 批量为扫描到的日期属性添加校验规则
        foreach (var prop in dateTypeProps)
        {
            BusinessRules.AddRule(new DateValidRule(prop)
            {
                Severity = RuleSeverity.Warning
            });
        }
    }
}

步骤2:业务实体继承基类并调用初始化方法

所有业务实体继承上述BusinessBase基类,在实体的规则初始化阶段直接调用基类的InitializeBusinessRules方法即可,不需要再逐个为DateTime属性手动添加规则:

public class UserInfo : BusinessBase
{
    // 现有属性定义保持不变
    public static readonly IPropertyInfo<DateTime> BornDateProperty = RegisterProperty(...);
    public static readonly IPropertyInfo<DateTime?> LegitimationDateProperty = RegisterProperty(...);
    // 其他属性...

    public UserInfo()
    {
        // 调用基类方法即可自动完成所有DateTime属性的规则注册
        InitializeBusinessRules();
        // 其他自定义规则可正常手动添加
    }
}

可选扩展:支持跳过指定属性校验

如果存在个别DateTime属性不需要应用DateValidRule,可以自定义一个排除特性,扫描时过滤掉标记了特性的属性即可:

  • 定义标记特性
[AttributeUsage(AttributeTargets.Field)]
public class SkipDateValidCheckAttribute : Attribute { }
  • 给不需要校验的属性元数据打上标记
[SkipDateValidCheck]
public static readonly IPropertyInfo<DateTime> InternalUpdateTimeProperty = RegisterProperty(...);
  • 在基类扫描逻辑中增加过滤条件
var dateTypeProps = GetType()
    .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
    .Where(field => field.FieldType == typeof(IPropertyInfo<DateTime>) 
                    || field.FieldType == typeof(IPropertyInfo<DateTime?>))
    // 过滤掉标记了跳过校验的属性
    .Where(field => !field.GetCustomAttributes(typeof(SkipDateValidCheckAttribute), false).Any())
    .Select(field => field.GetValue(this) as IPropertyInfo)
    .ToList();

该实现完全兼容现有规则执行逻辑,后续新增DateTime类型属性时不需要额外编写规则注册代码,从根源上避免手动逐个添加带来的效率低、易漏加的问题。

内容的提问来源于stack exchange,提问作者user3261212

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 08:06:18