脱离MVC的实体验证

MVC对模型验证提供了良好的支持。脱离了MVC框架又如何实现验证。做一下总结。

1.基于MVC DataAnnotations

 http://www.cnblogs.com/hjf1223/archive/2010/11/07/independent-dataannotation-validation.html

 

2. FluentValidation

废话不多说,FluentValidation和Autofac整合

 

首先是Model和Validator

public static IContainer container;

         [ClassInitialize()]

         public static void MyClassInitialize(TestContext testContext)

         {

             var builder = new ContainerBuilder();

             builder.RegisterType<Customer>();



             var typeFinder = new WebAppTypeFinder();

             var validators = typeFinder.FindClassesOfType(typeof(IValidator<>)).ToList();

             var TValidator = typeof(IValidator<>);

             foreach (var validator in validators)

             {

                 if (validator.IsGenericType)

                 {

                     continue;

                 }



                 //第一种

                 //var type = validator.BaseType.GetGenericArguments()[0];

                 //builder.RegisterType(type);

                 //builder.RegisterType(validator).As(TValidator.MakeGenericType(type)).SingleInstance();



                 //第二种

                 builder.RegisterType(validator)

                   .As(validator.FindInterfaces((type, criteria) =>

                   {

                       var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());

                       return isMatch;

                   }, typeof(IValidator<>)))

                   .SingleInstance();

             }

             

             container = builder.Build();

         }

 

注册IValidator

var builder = new ContainerBuilder();

             builder.RegisterType<Customer>();



             var typeFinder = new WebAppTypeFinder();

             var validators = typeFinder.FindClassesOfType(typeof(IValidator<>)).ToList();

             var TValidator = typeof(IValidator<>);

             foreach (var validator in validators)

             {

                 if (validator.IsGenericType)

                 {

                     continue;

                 }



                 //第一种

                 //var type = validator.BaseType.GetGenericArguments()[0];

                 //builder.RegisterType(type);

                 //builder.RegisterType(validator).As(TValidator.MakeGenericType(type)).SingleInstance();



                 //第二种

                 builder.RegisterType(validator)

                   .As(validator.FindInterfaces((type, criteria) =>

                   {

                       var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());

                       return isMatch;

                   }, typeof(IValidator<>)))

                   .SingleInstance();

             }

             

             container = builder.Build();

 

模型验证

[TestMethod]

        public void BaseTest()

        {

            var customer = new Customer();

            var validator = GetValidator<Customer>();

            var results = validator.Validate(customer);



            bool validationSucceeded = results.IsValid;

            Assert.IsFalse(validationSucceeded);



            IList<ValidationFailure> failures = results.Errors;

            Assert.AreNotEqual(1,failures.LongCount());

        }



        public IValidator<T> GetValidator<T>()

        {

            var instance = container.Resolve<IValidator<T>>();

            return instance;

        }

 

3.其他方式

微软企业库Validation Application Block (初级)

 

补充4.另一种实现

[TestMethod]

        public void Test1()

        {

            var model = new WorkFlow_Info_Meta();

            ClassValidator validator = new ClassValidator(model);

            validator.IsValid();

            foreach (var error in validator.ValidationErrors)

            {

                Console.WriteLine("Error in Person object: {0}", error.ErrorMessage);

            }

        }



        public class ClassValidator

        {

            

            public ClassValidator(object objectToValidate)

            {

                objectBeingValidated = objectToValidate;

            }



            private static object objectBeingValidated { get; set; }



            public List<ValidationResult> ValidationErrors { get; private set; }



            public bool IsValid()

            {

                if (objectBeingValidated != null)

                {

                    ValidationErrors = new List<ValidationResult>();

                    var context = new ValidationContext(objectBeingValidated,

                                                        null,

                                                        null);



                    bool isValid = Validator.TryValidateObject(objectBeingValidated,

                                                               context,

                                                               ValidationErrors);



                    if (!isValid)

                    {

                        return false;

                    }

                    return true;

                }

                return false;

            }

        }

  代码下载


参考:

http://www.cnblogs.com/hjf1223/archive/2010/11/07/independent-dataannotation-validation.html

Autofac: http://code.google.com/p/autofac/

fluentvalidation :http://fluentvalidation.codeplex.com/

你可能感兴趣的:(mvc)