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?
The
GetMetadataForProperty()is declared on the classModelMetadataProvider.AssociatedMetadataProviderderives fromModelMetadataProvider.CreateMetadata()is declared onAssociatedMetadataProvider. TheDataAnnotationsMetadataProviderthat 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
AssociatedMetadataProvideras you are in the link you provided, then your preferred extensibility point is theCreateMetadatamethod, 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: