问题描述
我们有相当需要访问库/数据库做好自己的工作了几验证方法。到目前为止,我们已经使用了服务定位器模式(尽管有节制地),以自定义ValidationAttributes做到这一点:
公众覆盖BOOL的IsValid(对象的值)
{
//使用自定义的服务定位在我们的应用程序的基础设施
VAR回购= DependencyInjector.Current.GetService< IXyzRepository>();
...
}
我知道这是在:(作为一种反模式,我们想用一个更正确的做法。我们用团结,我读的。然而说,该文件已过期(退役内容)。
该解决方案并不需要使用验证属性,我想它可以使用IValidatableObject,但问题依然存在:如何注入依赖到模型中。我们是否需要一个自定义的模型绑定做到这一点?
另一种解决方案是在控制器,其中,依赖注入容易执行验证。对我来说,这虽然感到混乱。我想该模型通过它获取到action方法的时间来验证。
此外,我们有时会用[RemoteAttribute]执行一些客户端上的这些验证的。目前,这些方法用静态方法Validator.TryValidateObject构造一个视图模型和委托检验的模型。
你是如何完成的,需要注入的依赖来完成工作验证,而不使用SL反模式?
I use FluentValidation.NET to perform validation in my applications. It allows me to inject dependencies into my validators. It has a really nice integration with ASP.NET MVC. It also supports automatic client side validation for the standard rules just the same way as data annotations using jquery unobtrusive validate:
- NotNull/NotEmpty
- Matches (regex)
- InclusiveBetween (range)
- CreditCard
- EqualTo (cross-property equality comparison)
- Length
I have never used data annotations to perform validation. They are absolutely useless when you need to handle some more complex validation scenarios where you need to validate dependent properties and even use some service. I put complex in italics in the previous sentence because, I don't think that validating that one of the 2 properties is required is a really complex validation scenario and yet, just checkout the amount of infrastructure crap you have to write in order to implement it using data annotations. Looking at this code you no longer know what you are validating.
这篇关于如何注入用于.NET MVC3验证依赖呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!