-
Beware of using the ThreadStaticAttribute in an ASP.NET environment
-
While implementing NAuthorize, I needed
an object registry on a per user/session basis as discussed in

The way this works in .NET is as follows (assuming ObjectRegistry is a collection class
and a singleton):
[ThreadStatic]
private static volatile ObjectRegistry _instance = null;
public static ObjectRegistry Instance
{
get
{
if(_instance == null)
{
lock(typeof(ObjectRegistry))
{
if(_instance == null)
{
_instance = new ObjectRegistry();
}
}
}
return(_instance);
}
}
The ThreadStatic attribute is what makes this work. The only gotcha so far is that this doesn't work in an ASP.NET application (Web/Webservice) as threads are reused for different requests, hence having the wrong ObjectRegistry serving the wrong user/session. The only solution I can think of for the time being, is having the ObjectRegistry detect if there's a HttpContext, and if so, subscribe to the EndRequest event of the associated HttpApplication and clear itself when the event fires.
UPDATE: Create your own
HttpContext class
from Brian Bilbro also provides a solution to this same problem.
The only thing worth checking out is that the CallContext is properly destroyed
when the web/webservice request is served.
-
Is this the B L O G use case diagram?
-
This is my
perception of blogging so far, considering I've only just started.
http://www10.brinkster.com/esealer/blogcase.png
[Sorry, brinkster doesn't
allow http referrers outside of its own domain.]