Create a Specification

Basic Specification

To create a Specification, add the SpecExpress namespace and create a class that inherits from Validates<T> where T is the class that the specification is validating. The add one or more Validation Expressions written using the SpecExpress DSL. Validation Expressions are created in the Specification's constructor. For example:

public class ContactSpecification : Validates<Contact>
{
    public ContactSpecification()
    {
        Check(c => c.FirstName).Required();
        Check(c => c.LastName).Required();
    }
}

Multiple Specifications for a Type

A system can have multiple specifications for a single Type. By registering a specification with the ValidationCatalog, the developer doesn't need to specify which specification to use to validate an object because the Validation Catalog will determine it by using the Specification for the Type that matches the Type of object being validated. In the case of multiple specifications registered, for example ContactSpecification and DeleteContactSpecification, the Catalog requires that one of the specifications be identified as default.

Default Specification

public class ContactSpecification : Validates<Contact>
{
    public ContactSpecification()
    {
        //Specify this Specification as the default specification for Contact
        IsDefaultForType();

        Check(c => c.FirstName).Required();
        Check(c => c.LastName).Required();       
    }
}

Additional Specification

public class DeleteContactSpecification : Validates<Contact>
{
    public ContactSpecification()
    {
        Check(c => c.Active).Required().And.IsFalse();
    }
}

Validate Instance

//This will use ContactSpecification because the Specification isn't specified and ContactSpecification is marked as Default.
var results = ValidationCatalog.Validate(contact);

//Validate using non-default Specification
var result = ValidationCatalog.Validate(contact, DeleteContactSpecification );


Last edited Jan 22, 2010 at 8:51 PM by TechnoAg, version 2

Comments

No comments yet.