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

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

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

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

最佳答案

我猜它被密封的原因是因为实际的 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;
      }
 }

关于asp.net - 如何扩展 CachedDataAnnotationsModelMetadataProvider?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19199084/

10-12 00:30
查看更多