我们希望使用 CachedDataAnnotationsModelMetadataProvider
照原样improves performance我们在 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/