Castle Windsor 和 Fluent Validation 作为 MVC 验证器
我已经将我的 MVC 项目设置为使用 Fluent Validation 和 Castle Windsor,一切都运行良好。我使用自定义验证器工厂是为了考虑到我也在使用实体框架,并且必须考虑包装在 POCO 类周围的动态代理。这是我的 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;
}
当控制器操作是模型绑定的模型存在验证器时,一切都运行良好。如果该特定模型不存在验证器,则会收到一条错误消息,指出 Windsor 无法解析该类型。
但是,并非所有模型都需要验证器。我可以写一个空的,但那只是无用的代码。当我尝试解析验证器时,我应该捕获错误并忽略它吗? Castle 中有内置的东西可以帮助我解决这个问题吗?我应该怎么办?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我最终做的就是在 ValidatorFactory 中捕获 ComponentNotFoundException 并返回 null,如下所示:
不完全确定这是最好的做法,但它似乎有效。
What I ended up doing with this was to catch the ComponentNotFoundException inside my ValidatorFactory and returning null like this:
Not completely sure it's the best thing to do, but it seems to work.