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
48 lines (39 loc) · 1.7 KB
/
ValidatorCache.cs
File metadata and controls
48 lines (39 loc) · 1.7 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
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using ServiceStack.FluentValidation;
using ServiceStack.ServiceHost;
namespace ServiceStack.ServiceInterface.Validation
{
public static class ValidatorCache
{
private static Dictionary<Type, ResolveValidatorDelegate> delegateCache
= new Dictionary<Type, ResolveValidatorDelegate>();
private delegate IValidator ResolveValidatorDelegate(IHttpRequest httpReq);
public static IValidator GetValidator(IHttpRequest 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(IHttpRequest httpReq)
{
return httpReq.TryResolve<IValidator<T>>();
}
}
}