forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidatorCache.cs
More file actions
53 lines (44 loc) · 1.83 KB
/
Copy pathValidatorCache.cs
File metadata and controls
53 lines (44 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using ServiceStack.Configuration;
using ServiceStack.FluentValidation;
using ServiceStack.Web;
namespace ServiceStack.Validation
{
public static class ValidatorCache
{
private static Dictionary<Type, ResolveValidatorDelegate> delegateCache
= new Dictionary<Type, ResolveValidatorDelegate>();
private delegate IValidator ResolveValidatorDelegate(IRequest httpReq);
public static IValidator GetValidator(IRequest httpReq, Type type)
{
ResolveValidatorDelegate parseFn;
if (delegateCache.TryGetValue(type, out parseFn)) return parseFn.Invoke(httpReq);
var genericType = typeof(ValidatorCache<>).MakeGenericType(type);
var mi = genericType.GetMethod("GetValidator", BindingFlags.Public | BindingFlags.Static);
parseFn = (ResolveValidatorDelegate)Delegate.CreateDelegate(typeof(ResolveValidatorDelegate), mi);
Dictionary<Type, ResolveValidatorDelegate> snapshot, newCache;
do
{
snapshot = delegateCache;
newCache = new Dictionary<Type, ResolveValidatorDelegate>(delegateCache);
newCache[type] = parseFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref delegateCache, newCache, snapshot), snapshot));
return parseFn.Invoke(httpReq);
}
}
public class ValidatorCache<T>
{
public static IValidator GetValidator(IRequest httpReq)
{
var validator = httpReq.TryResolve<IValidator<T>>();
var hasRequest = validator as IRequiresRequest;
if (hasRequest != null)
hasRequest.Request = httpReq;
return validator;
}
}
}