Why is Custom DataAnnotationsModelMetadataProvider's CreateMetadata never being called?

1k Views Asked by At

I created a custom provider by inheriting the DataAnnotationsModelMetadataProvider and overriding the CreateMetadata method:

public class CustomMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, 
        Type containerType, Func<object> modelAccessor, 
        Type modelType, string propertyName)
    {
        //... code not included for brevity but execution never gets here
    }
}

Then I registered it in Global.asax within MvcApplication class:

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        // Other code...
        System.Web.ModelBinding.ModelMetadataProviders.Current = 
            new CustomMetadataProvider();
    }
}

I put a breakpoint and the registration above is executing and Current is being set.

Problem/Question

The CreateMetadata method is never being called. What else do I need to do?

1

There are 1 best solutions below

7
On BEST ANSWER

You're setting the wrong property in your Global.asax.cs file. Instead of:

System.Web.ModelBinding.ModelMetadataProviders.Current = 
        new CustomMetadataProvider();

It should just be this:

ModelMetadataProviders.Current = 
        new CustomMetadataProvider();

Which if you really want to provide the full qualifier is actually:

System.Web.Mvc.ModelMetadataProviders.Current = 
        new CustomMetadataProvider();