将IClientValidatable保持在模型层之外 [英] Keeping IClientValidatable outside the model layer

查看:82
本文介绍了将IClientValidatable保持在模型层之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用数据注释来验证我的模型类.我也写了几个自定义属性.最终,将模型推送到内置于ASP.NET MVC的Web界面中,但是我想保持明确的关注点分离,因此模型类具有自己的程序集(也将由控制台应用程序使用).在模型层中必须使用IClientValidatable接口(这是一个与Web有关的问题),这打破了我想要的松散耦合.有想法该怎么解决这个吗?谢谢.

I'm using Data Annotations to validate my model classes. I wrote a couple of custom attributes as well. Ultimately, the model is pushed to a web interface built in ASP.NET MVC, but I want to keep a clean separation of concerns, so the model classes has its own assembly (which will also be used by console apps). Having to use the IClientValidatable interface (which is a web concern) in the model layer breaks the loose coupling I'm aiming for. Any ideas on how to fix this? Thanks.

推荐答案

您可以为数据注释属性添加适配器.

You can add adapter for data annotation attribute.

例如,您具有MyValidationAttribute.

For example you have MyValidationAttribute.

您需要添加如下适配器:

You need add adapter like following:

 public class MyValidationAttributeAdapter  : DataAnnotationsModelValidator<MyValidationAttribute>
    {
        public MyValidationAttributeAdapter(ModelMetadata metadata, ControllerContext context, MyValidationAttribute attribute) : base(metadata, context, attribute)
        {
        }

        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            //return client rule here
            return base.GetClientValidationRules();
        }
    }

在应用程序的某处开始添加代码,该代码注册了此适配器:

And somewhere on application start add code, which register this adapter:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyValidationAttribute), typeof(MyValidationAttributeAdapter));

这篇关于将IClientValidatable保持在模型层之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆