How to use the ValidationBlockExtension ?

Topics: Validation Application Block
Dec 6, 2011 at 6:40 PM
Edited Dec 6, 2011 at 6:48 PM

Hi,

I'm desperately looking for a sample about the ValidationBlockExtension. I tried to used it, but each time I do a resolve like unityContainer.Resolve<Validator<MyDataContract>>() unity throw me an exception. I tried many way, like:

 

var valFactory = EnterpriseLibraryContainer.Current.GetInstance<ValidatorFactory>();
var container = new UnityContainer();
container.RegisterInstance( valFactory );
container.Configure<Microsoft.Practices.EnterpriseLibrary.Validation.Configuration.Unity.ValidationBlockExtension>();
container.RegisterType<MyDataContract>();
var validator = container.Resolve<Validator<MyDataContract>>();

In this sample, the MyDataContract class is a simple POCO.

By the way, is it possible to get the ValidatorFactory directly fro a IUnityContainer ?
If yes, how to configure the container ?
Dec 6, 2011 at 9:56 PM

Here's how you configure the container and use the container to retrieve the Validator: 

    public class MyDataContract 
    { 
        [System.ComponentModel.DataAnnotations.Required]
        public string Province 
        { 
            get; set; 
        } 
    }

    class Program
    {
        static void Main(string[] args)
        {
            var container = new UnityContainer(); 

            container.AddNewExtension<EnterpriseLibraryCoreExtension>(); 
            container.AddNewExtension<ValidationBlockExtension>();
            
            var validator = container.Resolve<Validator<MyDataContract>>();
            var vr = validator.Validate(new MyDataContract());

            foreach (var result in vr) 
            { 
                Console.WriteLine(result.Message); 
            }
            //Outputs: The Province field is required.
        }
    }

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com

Dec 7, 2011 at 1:56 PM

Thank you very much :).

I knew I was just missing something !