This repository was archived by the owner on Jul 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHostContext.cs
More file actions
86 lines (72 loc) · 2.1 KB
/
HostContext.cs
File metadata and controls
86 lines (72 loc) · 2.1 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
using System;
using System.Collections;
using SimpleStack.Interfaces;
using System.Collections.Generic;
namespace SimpleStack
{
public class HostContext
{
public static readonly HostContext Instance = new HostContext();
[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(items == null)
items = new Dictionary<object, object>();
return items;
}
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();
}
}
}
}