In a synchronous environment, itβs easy to create a context that allows you to attach an out-of-band context to the current thread. Examples of this are the current TransactionScope context or stream-static log.
using (new MyContext(5)) Assert.Equal(5, MyContext.Current); Assert.Equal(null, MyContext.Current);
It is easy to implement context using a combination of IDisposable and a stream-static field .
Obviously, this is falling apart when using async methods because the context is based on a streaming static field. So this fails:
using (new MyContext(5)) { Assert.Equal(5, MyContext.Current); await DoSomethingAsync(); Assert.Equal(5, MyContext.Current); }
And, of course, we also want the context passed to the async methods in the call chain, so this should also work:
using (new MyContext(5)) { Assert.Equal(5, MyContext.Current); await AssertContextIs(5); }
Does anyone have an idea how this can be implemented? Losing out-of-band context when using the async / await pattern makes some pieces of code really ugly.
Think of async WebAPI calls where you want to use query-based context for logging. You want your registrar to be in the back of the call stack to know the request identifier, without having to pass that request identifier completely through the call stack using parameters.
Thanks for any help!
source share