views:

114

answers:

1

I have setup my MVC project to use Fluent Validation and Castle Windsor and everything is working wonderfully. I am using a custom Validator Factory to take into account that I am also using Entity Framework and have to account for the dynamic proxies that get wrapped around my POCO classes. Here is my CastleWindsorValidatorFactory:

public override IValidator CreateInstance( Type validatorType)
{
    if( validatorType.GetGenericArguments()[0].Namespace.Contains( "DynamicProxies" ) )
    {
        validatorType = Type.GetType( String.Format( "{0}.{1}[[{2}]], {3}", validatorType.Namespace, validatorType.Name, validatorType.GetGenericArguments()[0].BaseType.AssemblyQualifiedName, validatorType.Assembly.FullName ) );

    }

    return ResolveType.Of( validatorType ) as IValidator;
}

Everything is working well when a validator exists for the model that the controller action is model binding. If no validator exists for that particular model, then I get an error that Windsor can't resolve that type.

But, not all models need a validator. I can write an empty one, but that is just useless code. Should I just catch the error and ignore it when I'm trying to resolve a validator? Is there something built into Castle that will help me with this? What should I do?

A: 

What I ended up doing with this was to catch the ComponentNotFoundException inside my ValidatorFactory and returning null like this:

public class CastleWindsorValidatorFactory : ValidatorFactoryBase
{
    public override IValidator CreateInstance( Type validatorType)
    {
        if( validatorType.GetGenericArguments()[0].Namespace.Contains( "DynamicProxies" ) )
        {
            validatorType = Type.GetType( String.Format( "{0}.{1}[[{2}]], {3}", validatorType.Namespace, validatorType.Name, validatorType.GetGenericArguments()[0].BaseType.AssemblyQualifiedName, validatorType.Assembly.FullName ) );

        }

        try
        {
            return ResolveType.Of( validatorType ) as IValidator;
        }
        catch( ComponentNotFoundException )
        {
            return null;
        }
    }
}

Not completely sure it's the best thing to do, but it seems to work.

Brian McCord

related questions