How can I extend CachedDataAnnotationsModelMetadataProvider?

♀尐吖头ヾ 提交于 2019-12-05 18:20:53

I would guess that the reason it is sealed is because the actual CreateMetadata implementation contains caching logic that you should not be modifying.

To extend CachedDataAnnotationsModelMetadataProvider, I find that the following seems to work well:

 using System.Web.Mvc;

 public class MyCustomMetadataProvider : CachedDataAnnotationsModelMetadataProvider
 {
      protected override CachedDataAnnotationsModelMetadata CreateMetadataFromPrototype(CachedDataAnnotationsModelMetadata prototype, Func<object> modelAccessor)
      {
           var result = base.CreateMetadataFromPrototype(prototype, modelAccessor);

           //modify the base result with your custom logic, typically adding items from
           //prototype.AdditionalValues, e.g.
           result.AdditionalValues.Add("MyCustomValuesKey", prototype.AdditionalValues["MyCustomValuesKey"]);

           return result;
      }

      protected override CachedDataAnnotationsModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName)
      {
           CachedDataAnnotationsModelMetadata prototype = base.CreateMetadataPrototype(attributes, containerType, modelType, propertyName);

           //Add custom prototype data, e.g.
           prototype.AdditionalValues.Add("MyCustomValuesKey", "MyCustomValuesData");

           return prototype;
      }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!