2011-08-30 36 views
3

我重新提到了我的问题。WCF - 每个调用对象缓存

从我的WCF服务的服务器端代码,我想缓存一些变量。这些变量需要在整个服务调用的生命周期中使用。我不希望他们在可能用于服务逻辑的每个方法签名调用中。

如果这是一个web应用程序,我会使用会话管理,但这是在服务器端代码。我如何“缓存”每个服务调用的这些值,然后在服务完成时将它们处理掉?

解决方案:

的这点是跟踪哪些服务调用中的错误跟踪工具有一个错误。所以,最后我不喜欢的东西如下:

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; 
      } 
    } 
} 

使主调用的方法来捕获所有异常,然后我就可以使用这两个变量,我需要在顶层。

+0

我在这里读两个不同的问题:1)你想登录错误呼叫者ID和2)你有一组除了价值观的来电显示你想要访问来自服务调用栈中的任何地方。我对吗? – ErnieL

+0

对不起,我不明白这个问题,请问可以扩展它吗? – oleksii

回答

2

你的问题对我没有任何意义。

通过了一个服务调用的的LiveCycle

A“服务调用” - 或服务操作 - 仅仅是一个服务内的方法的调用。显然,当调用操作时(或从某处获取它们)需要传递值,因此您已经拥有它们。

public class MyService : IMyContract 
{ 
    public void DoSomething(string p1, int p2) 
    { 
     DoThing(p1); 
     DoAnotherThing(p2); 
    } 
} 

那么为什么参数需要缓存呢?根据需要在上下文中使用它们。

如果你的意思是缓存每个会话,这是更有意义。解决的方法是比较简单的:

// 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); 
    } 
} 
+0

我试图避免行DoThing(_P1);几乎像一个全局变量。 (虽然恨全局)。这给了我一个想法。谢谢。 – Arnej65

0

可能转到基于会话的模型,但我想这对于你想做的事情来说太重了。

我还想象你当前每次调用你的WCF服务都要传递这个id。

也就是说,您可以创建一个特定的异常类型,它将在构造函数中使用两个参数。第一个是调用者的ID(您将作为属性公开),第二个是将传递给base constructor of the Exception class并通过InnerException property公开的异常。