2 WCF方法之间的全局变量 [英] Global Variable between two WCF Methods

查看:289
本文介绍了2 WCF方法之间的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个方法:一个WCF服务说

I have two Methods in a WCF Service say

Method1()
{
 _currentValue = 10;
}

Method2()
{
return _currentValue;
}



我有一种情况是,我需要设置方法一(值),并在方法2阅读()

I have a situation in which, i need to set a value in Method1() and read it in Method2().

我试着用静态变量公开静态INT _currentValue ,我能够读取方法1()的方法2()设置的值。

I tried using static variable like public static int _currentValue, i could able to read the value set in Method1() in Method2().

但问题是,我想该变量像发每个请求单独的实例变量反应。也就是说,现在下面的问题。

But the issue is, i want this variable to react like separate instance variable for each request made. i.e., right now below is the problem

浏览器1:

 - Method1() is called
    => sets _currentValue = 10;
 - Method2() is called
    => returns _currentValue = 10;



浏览器2:

 - Method2() is called
    => returns _currentValue = 10;



其实值设置为浏览器1是静态的,所以在浏览器2
的值相同检索。

Actually the value set is Browser 1 is static, so in Browser 2 the same value is retrieved.

我想实现的是变量应该像做(每个浏览器调用时),为每个请求一个新的实例。我应该在这种情况下使用什么样的?会话?

What i am trying to implement is the variable should act like a new instance for each request made (when calling from each browser). What should i use in this case? a session?

推荐答案

您会需要某种机制的相关性,因为你必须调用到不同的方法两个完全不同的会话。因此,我建议使用私钥,这两个呼叫者知道了。

You're going to need some mechanism for correlation because you have two completely different sessions calling into different methods. So I would recommend using a private key that both callers know.

这是一个有点不可能的,我知道,键可以是什么,因为我真的不能收集什么从你的问题,所以只有自己知道,但一个简单的事实是,你会需要的相关性。现在,一旦你确定他们可以使用,你可以做这样的事情。

It is a bit impossible for me to know what that key can be because I can't really gather anything from your question, so only you know that, but the simple fact is you're going to need correlation. Now, once you determine what they can use you can do something like this.

public class SessionState
{
    private Dictionary<string, int> Cache { get; set; }

    public SessionState()
    {
        this.Cache = new Dictionary<string, int>();
    }

    public void SetCachedValue(string key, int val)
    {
        if (!this.Cache.ContainsKey(key))
        {
            this.Cache.Add(key, val);
        }
        else
        {
            this.Cache[key] = val;
        }
    }

    public int GetCachedValue(string key)
    {
        if (!this.Cache.ContainsKey(key))
        {
            return -1;
        }

        return this.Cache[key];
    }
}

public class Service1
{
    private static sessionState = new SessionState();

    public void Method1(string privateKey)
    {
        sessionState.SetCachedValue(privateKey, {some integer value});
    }

    public int Method2(string privateKey)
    {
        return sessionState.GetCachedValue(privateKey);
    }
}

这篇关于2 WCF方法之间的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆