A better context container

Suppose you want to share some context info between multiple methods / objects. In WCF you must use OperationContext.Current to store the data. In ASP.Net, you can use the session, or better the HttpContext.Items. For Windows Forms, you will have the ThreadStatic attribute. With my new implementation of an AmbientContext, we have a single store to share the context data in all of theses scenarios.

I've picked the idea here:

http://aabs.wordpress.com/2007/12/31/the-ambient-context-design-pattern-in-net/

and here:

http://msdn.microsoft.com/msdnmag/issues/06/09/NETMatters/default.aspx

OK, here is a sample code to use it:

public void Method1()
{
using (new AmbientContextScope())
{
AmbientContext.Current.SetLogicalValue(
"userInfo",
new UserInfo()
{
DisplayName = "Dany Laporte",
Username = "danlap"
});

this.ShowUserInContext();
}
}

public void ShowUserInContext()
{
if (AmbientContext.Current != null)
{
UserInfo userInfo = (UserInfo)AmbientContext.Current.GetLogicalValue("userInfo");
Console.WriteLine(userInfo.DisplayName);
}
}

With a context scope, you can copy the data upon multiple contexts or multiple threads easily. You can also create delegate that are scoped based on the current context.


using (new AmbientContextScope())
{
AmbientContext.Current.SetLogicalValue("myKey", "myValue");

ThreadPool.QueueUserWorkItem(
AmbientContext.Current.CreateScopedDelegate(
delegate(object state)
{
Console.WriteLine(AmbientContext.Current.GetLogicalValue("myKey"));
}));
}

Here is a simple class diagram of the actual implementation:



AmbientContextDiagram

Please tell me what you think?

0 comments: