Reputation: 3365
I have the following class
[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
}
}
}
And I have noticed that the Validator constructor only gets called once during my application. This is problematic because I access the HttpContext in the validator. How can I handle this situation ?
Thank you
Upvotes: 1
Views: 1814
Reputation: 3365
All right, the answer is in the source code. FluentValidation is caching the instance.
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;
}
}
}
I'll modify it and recompile from source. I don't want to use IoC to validate attach the validators to my ViewModels, I prefer to have everything defined in the same file for this usage, makes maintenance easier here.
Upvotes: 1