【问题标题】:How can I extend CachedDataAnnotationsModelMetadataProvider?如何扩展缓存数据注释 ModelMetadataProvider?
【发布时间】:2014-01-08 06:46:11
【问题描述】:

我们希望像 improves performance 一样使用 CachedDataAnnotationsModelMetadataProvider,并且我们在 MVC4 应用程序中使用了大量元数据。

我们目前正在创建一个自定义 ModelMetadataProvider,它继承自 DataAnnotationsModelMetadataProvider 并覆盖 CreateMetadata 属性以执行一些自动显示名称创建,例如从名称等中删除 Id。但是我们也想缓存它,所以我们想将我们的自定义 ModelMetadataProvider 基于 CachedDataAnnotationsModelMetadataProvider。

如果我们试图覆盖CreateMetadata,我们不能,因为它是密封的。它被密封的任何原因 - 我想我可以获得源代码并重新实现只是发现我无法扩展很奇怪?

有没有人做过类似的事情?

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-4 metadata modelmetadata


    【解决方案1】:

    我猜它被密封的原因是因为实际的CreateMetadata 实现包含你不应该修改的缓存逻辑。

    为了扩展CachedDataAnnotationsModelMetadataProvider,我发现以下似乎效果不错:

     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;
          }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多