如何防止FluentValidation缓存验证器类

时间:2015-06-01 11:35:29

标签: c# asp.net-mvc asp.net-mvc-5 fluentvalidation

我有以下课程

[Validator(typeof(MyViewModelValidator)]
public class MyViewModel
{
    public string Prop1 {get; set;}
    public string Prop1 {get; set;}

    public class MyViewModelValidator : AbstractValidator<MyViewModel>
    {
        public MyViewModelValidator()
        {
            //Stuff goes here
        }
    }
}

我注意到Validator构造函数只在我的应用程序中被调用一次。这是有问题的,因为我在验证器中访问HttpContext。我该如何处理这种情况?

谢谢

1 个答案:

答案 0 :(得分:1)

好的,答案是in the source code。 FluentValidation正在缓存实例。

public class InstanceCache {
        readonly Dictionary<Type, object> cache = new Dictionary<Type, object>();
    readonly object locker = new object();

    /// <summary>
    /// Gets or creates an instance using Activator.CreateInstance
    /// </summary>
    /// <param name="type">The type to instantiate</param>
    /// <returns>The instantiated object</returns>
    public object GetOrCreateInstance(Type type) {
        return GetOrCreateInstance(type, Activator.CreateInstance);
    }

    /// <summary>
    /// Gets or creates an instance using a custom factory
    /// </summary>
    /// <param name="type">The type to instantiate</param>
    /// <param name="factory">The custom factory</param>
    /// <returns>The instantiated object</returns>
    public object GetOrCreateInstance(Type type, Func<Type, object> factory) {
        object existingInstance;

        if(cache.TryGetValue(type, out existingInstance)) {
            return existingInstance;
        }

        lock(locker) {
            if (cache.TryGetValue(type, out existingInstance)) {
                return existingInstance;
            }

            var newInstance = factory(type);
            cache[type] = newInstance;
            return newInstance;
        }
    }
}

我将修改它并从源代码重新编译。我不想使用IoC来验证将验证器附加到我的ViewModel,我更喜欢在同一个文件中为此用法定义所有内容,这使得维护变得更容易。