WCF - per call object caching
I have re-worded my question.
From the server side code of my WCF services, I would lik开发者_开发知识库e to cache a few variables. These variables need to be used through out the livecycle of one service call. I don't want them in every method signature call that may be used in the services logic.
If it was a web applicaiton I would use session management, but this is on the server code side. How do I 'cache' these values, per service call, and then dispose of them on service completion?
Solution:
The point of this was to track which service call had a error in a bug tracking tool. So in the end I did something like the following:
public class MyService: IMyService
{
public String ServiceLogic(string var1, string var2, string id)
{
try{
DoingStuff.DoMoreStuff();
}
catch(exception ex)
{
var trapper = MyCustomErrorTrap(var1,var2);
throw new faultexpection<MyCustomErrorTrap>(trapper);
}
}
}
Public static class DoingStuff
{
public static void DoMoreStuff()
{
try{
if(blah.toString())
........
}
catch(exception ex)
{
throw;
}
}
}
Allowing the main calling method to trap all exceptions, I can then use the two variables that I need at the top level.
Your question doesn't really make sense to me.
through out the livecycle of one service call
A "service call" - or a service operation - is just an invocation of a method within a service. You obviously need to pass the values in when the operation is called (or retrieve them from somewhere), so you'll already have them.
public class MyService : IMyContract
{
public void DoSomething(string p1, int p2)
{
DoThing(p1);
DoAnotherThing(p2);
}
}
So why do the parameters need to be cached? Just use them within the context as required.
If you mean cached per session, that makes more sense. The solution is relatively simple:
// decorate your class like this
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyService : IMyContract
{
// these fields will persist until the session is closed
private string _p1;
private int _p2;
public void DoSomething(string p1, int p2)
{
_p1 = p1;
_p2 = p2;
}
// check that the _p1 and _p2 values are initialised before use
public void AnotherServiceOperation()
{
DoThing(_p1);
DoAnotherThing(_p2);
}
}
You could go to a Session-based model, but I imagine that's too heavy for what you want to do.
I also imagine that you currently pass the id with each call to your WCF service(s).
That said, you could create a specific exception type which would take two parameters in the constructor. The first is the id of the caller (which you would expose as a property) and the second is the exception which will be passed to the base constructor of the Exception
class and exposed through the InnerException
property.
精彩评论