ASP.NET MVC2 ModelMetadataProviders:重写 CreateMetadata() 和 GetMetadataForProperty() 之间有什么区别?
我开始探索该框架的扩展点,从 MetadataProviders 开始。我目前已经实现了 使用 RequiredAttribute
成功填充 ModelMetadata.IsRequired 属性,但我似乎找不到两者之间的区别 覆盖 CreateMetadata()
或 GetMetadataForProperty()
,因为这两个选项似乎都有效。
一般来说,我见过的示例都会重写CreateMetadata()
。
- 使用这两种选项的优点和缺点是什么?
- 是否存在其中其中一种是首选选项的情况?
另外:是否有任何好的资源(博客、书籍)可以从这个扩展点学习?
I'm statring to explore the framework's extension points, starting with MetadataProviders. I've currently implemented populating ModelMetadata.IsRequired property using RequiredAttribute
succesfully, but I can't seem to find the difference between
overriding CreateMetadata()
or GetMetadataForProperty()
, since both options seem to work.
In general, the examples I've seen override CreateMetadata()
.
- What are the pro and cons of using either options?
- Are there any scenarios where one of these are the preferred options?
As an extra: are there any good resources (blogs, books) to learn from this extension point?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
GetMetadataForProperty()
在类ModelMetadataProvider
上声明。AssociatedMetadataProvider
派生自ModelMetadataProvider
。CreateMetadata()
在AssociatedMetadataProvider
上声明。您提供的链接中覆盖的DataAnnotationsMetadataProvider
派生自AssociatedMetadataProvider
。MVC 框架调用
ModelMetadataProvider
的GetMetadataForProperty()
方法。重写
CreateMetadata()
对您有用的原因是AssociatedModelMetadataProvider
的GetMetadataForProperty()
的默认实现调用了创建元数据()。它看起来像这样:
}
如果您像在提供的链接中一样对
AssociatedMetadataProvider
进行子类化,那么您首选的扩展点是CreateMetadata
方法,因为AssociatedMetadataProvider.GetMetadataForProperty()
方法会预先验证CreateMetadata()
方法的约定。这样,您就知道,如果您的CreateMetadata()
方法中存在错误,您就已经知道错误的根源在您的方法中,而不是在传递给它的参数中。另外,如果您想知道的话,这里是
FilterAttributes()
方法的源代码:The
GetMetadataForProperty()
is declared on the classModelMetadataProvider
.AssociatedMetadataProvider
derives fromModelMetadataProvider
.CreateMetadata()
is declared onAssociatedMetadataProvider
. TheDataAnnotationsMetadataProvider
that is overridden in the link you provide is derived fromAssociatedMetadataProvider
.The MVC framework makes calls to
ModelMetadataProvider
'sGetMetadataForProperty()
method.The reason overriding
CreateMetadata()
is working for you is because theAssociatedModelMetadataProvider
's default implementation ofGetMetadataForProperty()
makes a call toCreateMetadata()
. It looks like this:}
If you are subclassing the
AssociatedMetadataProvider
as you are in the link you provided, then your preferred extensibility point is theCreateMetadata
method, because theAssociatedMetadataProvider.GetMetadataForProperty()
method pre-validates the contract of yourCreateMetadata()
method. That way, you know that if there is an error in yourCreateMetadata()
method, you already know that the source of the error is in your method and not in the arguments that were passed to it.Also, here is the source of the
FilterAttributes()
method, in case you were wondering: