Repository navigation
Creating Context classes
Whenever you need to pass data through your application, using parameters is the most common and most explicit way to do this. There are, however, cases where parameters are not your best option. One of those cases is when certain data is needed almost anywhere or when you don't exactly know up front where that data is needed. In these situations it might be a good idea to make this data available through a context, which can then be accessed from almost anywhere in the application.
The .NET Framework itself makes extensive use of contexts: ExecutionContext, HttpContext, SecurityContext, OperationContext, Transaction, etc. Most of these contexts make their data accessible through a static .Current property, which may or may not be initialized depending on when or where you access it:
// If you have not yet created a transaction, Transaction.Current is null.
Assert.IsNull(Transaction.Current);
using (var scope = new TransactionScope())
{
// Inside a TransactionScope, Transaction.Current has been set to the current transaction.
Assert.IsNotNull(Transaction.Current);
scope.Complete();
}It can occasionally be beneficial to create your own custom context in your applications. To this end, the Kingo framework contains the Context<T> class.
The Context<T> is basically just a container for a certain value, but it gives you fine control over when or where that value is accessible through the use of scopes. Just like the Transaction class, the Context<T> class has a .Current property that exposes the value it holds. In addition, it contains three methods that allow you override that value temporarily, each one providing a different level of visibility of that value:
public sealed class Context<TValue> : IDisposable
{
public Context(TValue defaultValue)
{
...
}
public TValue Current
{
get { ... }
}
public IDisposable OverrideThreadLocal(TValue value)
{
...
}
public IDisposable OverrideAsyncLocal(TValue value)
{
...
}
public IDisposable Override(TValue value)
{
...
}
}When you create a new instance of the Context<T> class, you can optionally provide a default value to store through its constructor. This value will then immediately be accessible through it's .Current property:
var context = new Context<int>(8);
Assert.AreEqual(8, context.Current);If you want to change the value of the context, you can do so by one of it's OverrideXyz() methods. If you want to override the value for the current thread only, use the OverrideThreadLocal(T) method:
var context = new Context<int>(8);
using (context.OverrideThreadLocal(10))
{
// The value has now changed to '10', but only on the current thread.
// Other threads will still read the value '8'.
Assert.AreEqual(10, context.Current);
}
// The value of Current has now be changed back to '8'.
Assert.AreEqual(8, context.Current);If you use async/await extensively, thread local storage may be too limited. When you want the scope to span your entire asynchronous flow, use the OverrideAsyncLocal(T) method, which changes a value on all threads that share the same ExecutionContext:
var context = new Context<int>(8);
using (context.OverrideAsyncLocal(10))
{
var result = await GetSomethingAsync();
// The value is now '10', even though we might be running on a different thread
// than the one the scope was created on.
Assert.AreEqual(10, context.Current);
}
// The value of Current has now be changed back to '8'.
Assert.AreEqual(8, context.Current);Finally, if you simply want to perform a 'static' update of a value, visible to all threads that read the .Current property, use the Override(T) method:
var context = new Context<int>(8);
using (context.Override(10))
{
// The Default Scope is like a static setter that makes its value visible on any thread
// in your AppDomain.
using (ExecutionContext.SuppressFlow())
{
Task.Run(() => Assert.AreEqual(10, context.Current));
}
}
// The value of Current has now be changed back to '8'.
Assert.AreEqual(8, context.Current);In the previous paragraph explained how you can use the OverrideXyz(T) methods to temporarily override or set the value of the context. There are, however, some limitations on how you can nest or combine these methods. First of all, scopes should always be correctly nested. That means that as soon as a scope is created, it must also be the disposed before its parent (outer) scope is disposed. So this is legal:
using (context.Override(5))
{
using (context.Override(9))
{
}
}But this is not:
using (var outerScope = context.Override(5))
{
using (context.Override(9))
{
// Illegal! Exception is thrown here...
outerScope.Dispose();
}
}Another limitation is that a scope can only be created if it is at least as restrictive as its parent scope. That means that you can create a thread local scope inside a default scope, but not the other way around:
// This is allowed: every nested scope is at least as restrictive as its parent scope.
using (context.Override(1))
{
using (context.OverrideAsyncLocal(2))
{
using (context.OverrideThreadLocal(3))
{
}
}
}
// This is illegal, because the thread local scope is more restrictive than the async local scope.
using (context.OverrideThreadLocal(3))
{
// Exception is thrown here...
using (context.OverrideAsyncLocal(2))
{
}
}The Context<T> class provides some nice features on its own but is actually meant to be wrapped inside another, custom context class that only exposes the scopes you want to support and provides more fine-grained control over what value(s) are allows to be stored in your context. A common design is as follows:
- Create (or take) an interface of the type you would like to store, such as
IVehicle - Create a custom class, such as
Vehicle, that implements this interface, and implement it as follows:
public sealed class Vehicle : IVehicle
{
// Interface members here...
#region [====== Current ======]
public static readonly IVehicle Default = new Vehicle();
private static readonly Context<IVehicle> _Context = new Context<IVehicle>(Default);
public static IVehicle Current
{
get { return _Context.Current; }
}
public static IDisposable OverrideThreadLocal(IVehicle vehicle)
{
if (vehicle == null)
{
throw new ArgumentNullException("vehicle");
}
return _Context.OverrideThreadLocal(vehicle);
}
#endregion
}The actual design of the Vehicle class and whether or not a Default value exists is not relevant. What matters is that you typically declare a private static readonly variable of type Context<T> inside the class and then expose it's .Current value through a static .Current property of your own class. You can then choose which of the three OverrideXyz(T) methods you'd like to support yourself. In this case, we chose to only expose the thread local scope, but also to prevent any client code from storing a null value in the context.
Note that the Clock class also uses this design to make the current clock accessible anywhere in your code through its static Clock.Current property. Take a look at it if you haven't already done so.