[我正在回答我自己的问题(问答风格),但我不相信这是一个理想的解决方案。如果您有更好的方法(例如只需要配置的方法),请发表评论或留下替代答案。]
不是PropertyAccess
直接传递给单例类,而是传递 a PropertyAccessLocator
,它可用于根据PropertyAccess
需要获取当前请求的 。
这是 PropertyAccessLocator
public class PropertyAccessLocator
{
public PropertyAccess Get()
{
return DependencyResolver.Current.GetService<PropertyAccess>();
}
}
这是一个示例 ModelMetadataProvider
public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
private readonly PropertyAccessLocator _propertyAccessLocator;
public CustomModelMetadataProvider(
PropertyAccessLocator propertyAccessLocator)
{
_propertyAccessLocator = propertyAccessLocator;
// required because PropertyAccess is request scoped
// while this class is a singleton
}
protected override ModelMetadata CreateMetadata(
IEnumerable<Attribute> attributes,
Type containerType,
Func<object> modelAccessor,
Type modelType,
string propertyName)
{
var metadata = base.CreateMetadata(
attributes, containerType, modelAccessor, modelType, propertyName);
var propertyAccess = _propertyAccessLocator.Get();
// todo use propertyAccess to do something with the metadata...
return metadata;
}
}