Enterprise Library 5.0 中的Validators

  自.NET 4.0的一系列相关技术发布后,重装了WINDOWS。。重装了Visual Studio。。重装了SQL Server等等,真是微软牵一发动我全身。昨晚下载了Enterprise Library 5.0的组件,过去我使用4.1开发的项目中,大量应用了这个框架的Validation相关组件,它的设计的确很不错。不过昨天当我使用新版本的时候,出现了一些毫无头绪的编译错误。

  What?所有在Microsoft.Practices.EnterpriseLibrary.Validation.Validators空间下的验证器类都出现了这样的错误。它怎么就不是一个attribute class呢?反正可以看源代码,当然去看一下到底发生什么事。首先看一下这个ValidatorCompositionAttribute类的定义:

代码
namespace Microsoft.Practices.EnterpriseLibrary.Validation.Validators
{
/// <summary>
/// Indicates that the kind of composition to use when multiple <see cref="ValidatorAttribute"/> instances
/// are bound to a language element.
/// </summary>
/// <seealso cref="ValidatorAttribute"/>
[AttributeUsage(AttributeTargets.Property
| AttributeTargets.Field
| AttributeTargets.Method
| AttributeTargets.Parameter
| AttributeTargets.Class,
AllowMultiple
= true,
Inherited
= false)]
public sealed class ValidatorCompositionAttribute : BaseValidationAttribute
{
private CompositionType compositionType;
/// <summary>
/// Initializes a new instance of the <see cref="ValidatorCompositionAttribute"/> class.
/// </summary>
/// <param name="compositionType">The <see cref="CompositionType"/> to be used.</param>
public ValidatorCompositionAttribute(CompositionType compositionType)
{
this.compositionType = compositionType;
}

internal CompositionType CompositionType
{
get { return compositionType; }
}
}
}

它继承自BaseValidationAttribute类,不用看下去,它肯定是一个attribute class,因为它的类定义都已经使用了只有从Attribute中继承的类才能使用的特性——AttributeUsage。毫无头绪,唯有上官网看下这个版本的一些变动。该文档地址是:http://entlib.codeplex.com/wikipage?title=EntLib5ChangeLog&#vab

  截图里面说明了关于Validation框架的一些变动,尤其是最后一点,说自定义的验证器类必须继承自ValueValidatorAttribute,而不是ValidatorAttribute,否则可能会出现错误。于是我又跑去看刚才BaseValidationAttribute的定义:

晕,原来BaseValidationAttribute继承自ValidatorAttribute类,难道就是这里出了问题?不过尽管如此,我没办法改动它啊。于是我留意到,Enterprise Library 5.0的验证组件好像加入了Data Annotation的支持,而Data Annotation的相关组件是System.ComponentModel.DataAnnotations.dll,怀着碰下运气的心态,我在项目中加入了这个组件的引用。Bingo~!所有编译错误消失无踪。原来Enterprise Library 5.0的验证器类在实现上需要使用到Data Annotation,过去是不用的。问题总算结果了。

posted @ 2010-05-12 15:22  DOF_KL  阅读(1369)  评论(3编辑  收藏  举报