我已经重新表述了我的问题。
在我的 WCF 服务的服务器端代码中,我想缓存一些变量。这些变量需要在一个服务调用的整个生命周期中使用。我不希望它们出现在服务逻辑中可能使用的每个方法签名调用中。
如果它是一个 Web 应用程序,我会使用 session 管理,但这是在服务器代码端。我如何在每次服务调用时“缓存”这些值,然后在服务完成时处理它们?
解决方法:
这样做的目的是在错误跟踪工具中跟踪哪个服务调用有错误。所以最后我做了类似下面的事情:
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;
}
}
}
允许主调用方法捕获所有异常,然后我可以在顶层使用我需要的两个变量。
最佳答案
你的问题对我来说真的没有意义。
through out the livecycle of one service call
“服务调用” - 或服务操作 - 只是在服务中调用方法。您显然需要在调用操作时传递值(或从某处检索它们),因此您已经拥有它们。
public class MyService : IMyContract
{
public void DoSomething(string p1, int p2)
{
DoThing(p1);
DoAnotherThing(p2);
}
}
那么为什么需要缓存参数呢?只需根据需要在上下文中使用它们即可。
如果您的意思是每个 session 缓存,那更有意义。解决方法比较简单:
// 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);
}
}
关于c# - WCF - 每次调用对象缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7245895/