forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestContext.cs
More file actions
87 lines (75 loc) · 2.69 KB
/
RequestContext.cs
File metadata and controls
87 lines (75 loc) · 2.69 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
using System;
using System.Collections;
using System.Collections.Generic;
namespace ServiceStack
{
public class RequestContext
{
public static readonly RequestContext Instance = new RequestContext();
[ThreadStatic]
private static IDictionary items; //Thread Specific
/// <summary>
/// Gets a list of items for this request.
/// </summary>
/// <remarks>This list will be cleared on every request and is specific to the original thread that is handling the request.
/// If a handler uses additional threads, this data will not be available on those threads.
/// </remarks>
public virtual IDictionary Items
{
get
{
#if !(SILVERLIGHT || ANDROID)
return items ?? (System.Web.HttpContext.Current != null
? System.Web.HttpContext.Current.Items
: items = new Dictionary<object, object>());
#else
return items ?? (items = new Dictionary<object, object>());
#endif
}
set { items = value; }
}
public T GetOrCreate<T>(Func<T> createFn)
{
if (Items.Contains(typeof(T).Name))
return (T)Items[typeof(T).Name];
return (T) (Items[typeof(T).Name] = createFn());
}
public void EndRequest()
{
items = null;
}
/// <summary>
/// Track any IDisposable's to dispose of at the end of the request in IAppHost.OnEndRequest()
/// </summary>
/// <param name="instance"></param>
public void TrackDisposable(IDisposable instance)
{
if (instance == null) return;
if (instance is IService) return; //IService's are already disposed right after they've been executed
DispsableTracker dispsableTracker = null;
if (!Items.Contains(DispsableTracker.HashId))
Items[DispsableTracker.HashId] = dispsableTracker = new DispsableTracker();
if (dispsableTracker == null)
dispsableTracker = (DispsableTracker) Items[DispsableTracker.HashId];
dispsableTracker.Add(instance);
}
}
public class DispsableTracker : IDisposable
{
public const string HashId = "__disposables";
List<WeakReference> disposables = new List<WeakReference>();
public void Add(IDisposable instance)
{
disposables.Add(new WeakReference(instance));
}
public void Dispose()
{
foreach (var wr in disposables)
{
var disposable = (IDisposable)wr.Target;
if (wr.IsAlive)
disposable.Dispose();
}
}
}
}