forked from ThatRendle/Simple.Data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConcreteObject.cs
More file actions
44 lines (38 loc) · 1.33 KB
/
ConcreteObject.cs
File metadata and controls
44 lines (38 loc) · 1.33 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
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Simple.Data
{
internal class ConcreteObject
{
private static readonly object CastFailureObject = new object();
private WeakReference _concreteObject;
public object Get(Type type, IDictionary<string,object> data)
{
if (_concreteObject == null || !_concreteObject.IsAlive)
{
return ConvertAndCacheReference(type, data);
}
if (!ReferenceEquals(CastFailureObject, _concreteObject.Target))
{
return _concreteObject.Target;
}
return null;
}
private object ConvertAndCacheReference(Type type, IDictionary<string, object> data)
{
_concreteObject = null;
object result;
if (ConcreteTypeCreator.Get(type).TryCreate(data, out result))
{
Interlocked.CompareExchange(ref _concreteObject, new WeakReference(result), null);
return _concreteObject.Target;
}
Interlocked.CompareExchange(ref _concreteObject, new WeakReference(CastFailureObject), null);
return null;
}
}
}