c# - WCF - 每次调用对象缓存

标签 c# wcf

我已经重新表述了我的问题。

在我的 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/

相关文章:

WCF服务: Returning custom objects

c# - Sybase AdoNet4 AseClient v16.x (客户端无法建立连接)

C# 测试 null

c# - asp.net mvc 5 cookies 不持久在本地服务器上

wcf - ???-托管的 WCF 服务有多贵?

asp.net-mvc-3 - 从 ASP .NET MVC3 调用 WCF 服务的最佳做法是什么?

javascript - 如何在 jQuery 中使用 WCF 方法

c# - .net 桌面应用程序 - 如何存储/更改应用程序设置或连接字符串?

c# - 从C#执行多行PowerShell脚本

wcf - aspNet兼容性启用="true"