views:

154

answers:

2
CustomerValidator: AbstractValidator<Customer>

How might one dynamically instantiate the class above if passed an instance of a Customer?? Similarly if I had:

Cat c = new Cat();

I would want to dynamically invoke the class that implements

AbstractValidator<Cat>
+2  A: 

One common approach (if you own both Customer and CustomerValidator) is to decorate the class with the class that provides validation, via an attribute:

[Validator(typeof(CustomerValidator))]
public class Customer { }

Note that you may find it easier to work outside of generics, perhaps via an interface (note: no methods etc shown here):

public interface IValidator { }
public class CustomerValidator : AbstractValidator<Customer> {}
public class AbstractValidator<T> : IValidator where T : class {}

Then obtain the correct validator via reflection:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ValidatorAttribute : Attribute
{
    public Type ValidatorType { get; private set; }
    public ValidatorAttribute(Type validatorType)
    {
        ValidatorType = validatorType;
    }
    public static IValidator GetValidator(object obj)
    {
        if (obj == null) return null;
        return GetValidator(obj.GetType());
    }
    public static IValidator GetValidator(Type type)
    {
        if (type == null) return null;
        ValidatorAttribute va = (ValidatorAttribute)
            Attribute.GetCustomAttribute(type, typeof(ValidatorAttribute));
        if (va == null || va.ValidatorType == null) return null;
        return (IValidator) Activator.CreateInstance(va.ValidatorType);
    }
}

So calling GetValidator should return null or a suitable IValidator.

You can use generics in the above - but it usually creates more problems than it solves in example like this.

Marc Gravell
Bloody brilliant...if only i could up vote more..Cheers.
Schotime
No problem - any problems, post a comment.
Marc Gravell
A: 

Hi,

I recommend you to refer to a Solution Proposed by Imaar Spaanjaars which he has provided in a series of articles he wrote for "N-Layered Web Applications with ASP.NET 3.5". The Part 2 of the series has the solution to exactly what you require. I have successfully implemented this solution in my Model and it's working absolutely perfect.

Here's the Link:

link text

Also refer Part 3 which discusses advanced scenrio for Validations.

this. __curious_geek