ObjectContextManager uses one ObjectContext for multiple threads?

ObjectContextManager uses one ObjectContext for multiple threads?

Old forum URL: forums.lhotka.net/forums/t/6354.aspx


sidwall posted on Friday, February 06, 2009

Hi,

as I understand the Csla.Data.ObjectContextManager uses one ObjectContext for multiple threads. According to the following post that can cause problems:

http://dotnetslackers.com/articles/ado_net/Managing-Entity-Framework-ObjectContext-lifespan-and-scope-in-n-layered-ASP-NET-applications.aspx

In short:
If you host your Business Layer on a application server several threads can access DataPortal_Insert, DataPortal_Update, etc at the same time. They will all use the same ObjectContext to make there updates to the database.

Regards,
Anders Sidwall

ajj3085 replied on Friday, February 06, 2009

Hmm.. should be a simple enough fix.  If you slap a ThreadStatic attribute on the field that holds the dictionary of connections, that should take care of this issue.

I wonder if this same problem would occur for L2S DataContext. 

EDIT:  Opps... it uses LocalContext.  So this might be a bit more complex then I first thought.

EDIT2:  this shouldn't be a problem actually; LocalContext is already thread specific.  Whew.

sidwall replied on Thursday, February 12, 2009

I noticed that too. False alarm on my behalf. That Rocky fellow sure thinks about everything :)

 

RockfordLhotka replied on Thursday, February 12, 2009

There is one scenario (I can think of) where this might pose a problem.

When CSLA runs inside ASP.NET it can't use thread-local storage (TLS) because that's off limits in ASP.NET. So LocalContext is maintained in HttpContext.Current.

My guess is that if you manually spin up worker threads in ASP.NET you might end up with those threads sharing the same HttpContext, and thus the same LocalContext, and thus the same ObjectContextManager.

In my view that is outside of my scope, and you'll just have to not use ObjectContextManager. Without TLS or a per-thread HttpContext there's no way I know of to store per-thread data, so this problem becomes intractable.

Then again, maybe ASP.NET is smart enough to create a unique HttpContext for each thread you create...

Copyright (c) Marimer LLC