-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathResourceTypeRegistry.cs
More file actions
90 lines (77 loc) · 3.25 KB
/
ResourceTypeRegistry.cs
File metadata and controls
90 lines (77 loc) · 3.25 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.Collections.Generic;
namespace JSONAPI.Core
{
/// <summary>
/// Default implementation of IModelRegistry
/// </summary>
public class ResourceTypeRegistry : IResourceTypeRegistry
{
private readonly IDictionary<string, IResourceTypeRegistration> _registrationsByName;
private readonly IDictionary<Type, IResourceTypeRegistration> _registrationsByType;
/// <summary>
/// Creates a new ResourceTypeRegistry
/// </summary>
public ResourceTypeRegistry()
{
_registrationsByName = new Dictionary<string, IResourceTypeRegistration>();
_registrationsByType = new Dictionary<Type, IResourceTypeRegistration>();
}
public bool TypeIsRegistered(Type type)
{
var registration = FindRegistrationForType(type);
return registration != null;
}
public IResourceTypeRegistration GetRegistrationForType(Type type)
{
var reg = FindRegistrationForType(type);
if (reg == null)
throw new TypeRegistrationNotFoundException(type);
return reg;
}
public IResourceTypeRegistration GetRegistrationForResourceTypeName(string resourceTypeName)
{
lock (_registrationsByName)
{
IResourceTypeRegistration registration;
if (!_registrationsByName.TryGetValue(resourceTypeName, out registration))
throw new TypeRegistrationNotFoundException(resourceTypeName);
return registration;
}
}
public void AddRegistration(IResourceTypeRegistration registration)
{
lock (_registrationsByType)
{
lock (_registrationsByName)
{
if (_registrationsByType.ContainsKey(registration.Type))
throw new InvalidOperationException(String.Format("The type `{0}` has already been registered.",
registration.Type.FullName));
if (_registrationsByName.ContainsKey(registration.ResourceTypeName))
throw new InvalidOperationException(
String.Format("The resource type name `{0}` has already been registered.",
registration.ResourceTypeName));
_registrationsByType.Add(registration.Type, registration);
_registrationsByName.Add(registration.ResourceTypeName, registration);
}
}
}
private IResourceTypeRegistration FindRegistrationForType(Type type)
{
lock (_registrationsByType)
{
var currentType = type;
while (currentType != null && currentType != typeof(Object))
{
IResourceTypeRegistration registration;
if (_registrationsByType.TryGetValue(currentType, out registration))
return registration;
// This particular type wasn't registered, but maybe the base type was.
currentType = currentType.BaseType;
}
}
return null;
}
}
}