So here is the question : is there any way to create a Context that will be share only a part of the code. I don’t really know how to explain it, so I will make an example.
Suppose that I have :
using(Context ctx = new Context())
{
ctx.Set("abc","abc");
method1();
method2();
}
and (same for method 2) :
public void method1()
{
Context ctx = Context.Instance();
string abc = ctx.Get("abc");
}
The goal is that the Context.Instance() in the methods return the object created in the using but it must remains thread safe. What I mean is that if call is made from outside a using, or inside another using at the same time, it will return the context according to the using. And Context.Instante() will return a new Context if not exist (or null, I will adapt after, that’s not the point).
I know this is not classic way of doing it but I don’t want to have to pass the context at each call. The real method will have lots of subs methods and only the lasts will need it, but it must be common since the beginning.
The goal is to create one transaction that will be shared to all (and only) submethods, but the top methods don’t have access to EF classes. The only solution I have is to use the session to store my EF Context, or in static for batches since they don’t have session. That’s my goal, but the problem is much more generic.
I hope I’m clear, don’t hesitate to ask questions. And add tags since I don’t really know what tags add.
Thanks !
EDIT
I might not have been clear enough. Singleton is not enough, the static is shared between all the instance. If two call to the using are done in the same time by two different user, the Context will be the same to them, but I want them different.
Ideally, I would like to allow things like :
using(Context ctx = new Context())
{
ctx.Set("abc","abc");
method1();
using(Context ctx = new Context())
{
ctx.Set("abc","def");
method2();
}
method1();
}
But I think I ask too much.
Have your Context.Instance() method manage a thread static variable. The first call can create the instance, other calls can use it, and at the end of the using of the first call, you destroy it.
Using the thread-static approach, no multi threading problems should arise, since each thread has its own instance. In a single thread, every ‘next method execution’ will use the same instance.
UPDATE:
Some code. If I debug through it, only a single context is created, the second using statement receives the same context as the first using statement.