【问题标题】:Automatic property validation自动属性验证
【发布时间】:2014-05-21 11:19:50
【问题描述】:

有时,我有非常复杂的模型,其中包含许多需要在设置时验证的字符串属性,但是验证通常不会比 IsNotNullOrWhitespace 更进一步。

这通常会导致不必要的代码重复,所以我想知道是否有一种方法可以自动验证属性设置器值,最好不需要任何额外的框架。

可能的解决方案

  • AOP(例如使用 PostSharp)
  • 流畅的验证
  • 数据注释

Data Annotations 对我来说是最自然的方式,因为验证非常接近模型,并且因为它是 .Net-Framework 的一部分,所以属性还可以。但是,如果我在 MVC 或序列化之外使用模型,则必须使用验证器手动进行验证。所以我可能必须在很多地方(存储库、API、服务)进行验证,如果我忘记在某个地方这样做,我的域规则可能会被破坏。

AOP 可能是完美的方式,但是在 C# 中并没有直接这样的东西,并且将我的域模型与 PostSharp 或 Ninject(拦截)等基础架构组件紧密耦合是不行的。

【问题讨论】:

  • 何时需要进行验证?当@setter,是的,你应该使用AOP。您可以查看免费的 Fody (github.com/Fody/Fody)。也许这会减少您对耦合到基础架构组件的担忧。无论如何,我要问:您是否愿意拥有更多代码并为其付费并一遍又一遍地进行维护,或者您宁愿依赖基础架构组件,加快开发速度并减少出现错误的机会?什么是基础设施组件,什么不是?您是依赖 VS 还是使用(任何)文本编辑器,因为耦合太困扰您? ;-)

标签: c# validation ninject aop postsharp


【解决方案1】:

试试NConcern AOP Framework

这个新的最小运行时 AOP 框架(我积极研究它)可以帮助您管理 AOP 验证,而无需耦合您的域程序集。

在您的验证程序集中,定义您自己的验证属性以及如何验证它。

定义/识别电子邮件的自定义属性

[AttributeUsage(AttributeTargets.Property)]
public class Email : Attribute
{
    //validation method to use for email checking
    static public void Validate(string value)
    {
        //if value is not a valid email, throw an exception!
    }
}

检查代码合约的验证方面

//Validation aspect handle all my validation custom attribute (here only email)
public class EmailValidation : IAspect
{
    public IEnumerable<IAdvice> Advise(MethodInfo method)
    {
        yield return Advice.Before((instance, arguments) =>
        {
            foreach (var argument in arguments)
            {
                if (argument == null) { continue; }
                Email.Validate(argument.ToString());
            }
        });
    }
}

您的域程序集

public class Customer
{
    [Email]
    public string Login { get; set; }
}

进入另一个程序集(验证和域之间的链接

//attach validation to Customer class.
foreach (var property in typeof(Customer).GetProperties())
{
    if (property.IsDefined(typeof(Email), true))
    {
        Aspect.Weave<Validation>(property.GetSetMethod(true));
    }
}

【讨论】:

    猜你喜欢
    • 2013-05-16
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多