【问题标题】:How to prevent FluentValidation from caching the validator class如何防止 FluentValidation 缓存验证器类
【发布时间】:2015-06-01 11:35:28
【问题描述】:

我有以下课程

[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。我该如何处理这种情况?

谢谢

【问题讨论】:

  • 该用户解决了类似问题:stackoverflow.com/questions/17005146/…
  • Thanls,是的,我见过这个问题,但我知道我不能使用单例。我的问题更多:为什么我的代码表现为单例,我该如何防止这种情况。

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


【解决方案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,我更喜欢将所有内容都定义在同一个文件中以用于此用途,这样可以更轻松地进行维护。

【讨论】:

  • 嗨@readdy,只是想知道是否有可能从缓存中按需刷新某个类型的现有实例并重新创建它。移除缓存会对视图渲染产生巨大的性能影响。
猜你喜欢
  • 1970-01-01
  • 2012-10-23
  • 1970-01-01
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多