Introduction
Sometimes I need to store data scoped by some context and isolated from the other scopes.
If I'm building a library that is to be used in both Windows client and Web server environments, I have different isolation/scope needs: for a Web server environment, the scope is the current HTTP context; for a Windows client environment, the scope is the current process.
Defining the Contract
The needs for this store are simple, just a dictionary of objects with an object key.
public interface IScopedContextStore
{
object this[object key] { get; set; }
void Clear();
}
Concrete Implementations
The implementations are also simple.
Static Scoped Context Store
This store is scoped by application domain and uses a static Hashtable
.
public class StaticScopedContextStore : IScopedContextStore
{
private static Hashtable store = new Hashtable();
#region IScopedContextStore Members
public object this[object key]
{
get
{
return StaticScopedContextStore.store[key];
}
set
{
StaticScopedContextStore.store[key] = value;
}
}
public void Clear()
{
StaticScopedContextStore.store.Clear();
}
#endregion
}
Thread Static Scoped Context Store
This store is scoped by thread, and uses a thread static Hashtable
.
public class ThreadStaticScopedContextStore : IScopedContextStore
{
[ThreadStatic]
private static Hashtable store;
private static Hashtable Store
{
get
{
if (ThreadStaticScopedContextStore.store == null)
{
ThreadStaticScopedContextStore.store = new Hashtable();
}
return ThreadStaticScopedContextStore.store;
}
}
#region IScopedContextStore Members
public object this[object key]
{
get
{
return ThreadStaticScopedContextStore.Store[key];
}
set
{
ThreadStaticScopedContextStore.Store[key] = value;
}
}
public void Clear()
{
ThreadStaticScopedContextStore.Store.Clear();
}
#endregion
}
HTTP Context Scoped Context Store
This store is scoped by HTTP context (suited for Web server applications), and uses a Hashtable
stored in the current HttpContext
instance.
public class HttpContextScopedContextStore : IScopedContextStore
{
private static readonly object httpContextKey = new object();
private static Hashtable Store
{
get
{
Hashtable hashtable =
HttpContext.Current.Items[httpContextKey] as Hashtable;
if (hashtable == null)
{
HttpContext.Current.Items[httpContextKey] =
hashtable = new Hashtable();
}
return hashtable;
}
}
#region IScopedContextStore Members
public object this[object key]
{
get
{
return HttpContextScopedContextStore.Store[key];
}
set
{
HttpContextScopedContextStore.Store[key] = value;
}
}
public void Clear()
{
HttpContextScopedContextStore.Store.Clear();
}
#endregion
}