Global variable between two WCF methods

I have two methods in the WCF service:

Method1()
{
 _currentValue = 10;
}

Method2()
{
return _currentValue;
}

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

I tried using a variable staticlike public static int _currentValue, I was able to read the value set in Method1 () in Method2 ().

But the problem is that I want this variable to react as a separate instance variable for each request made. that is right now below is the problem

Browser 1:

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

Browser 2:

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

In fact, the set of values ​​- this browser 1 is static, so the same value is retrieved in browser 2.

, , - , ( ). ? ?

+5
5

, , . , .

, , , , , . , , , - .

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

static, . static , , , , , , :

private int _currentValue;

Method1() 
{ 
    _currentValue = 10; 
} 

Method2() 
{ 
    return _currentValue; 
} 

. . ( - .)

+2

WCF WCF:

  • Persession

,

WCF

0

, - , , WCF . () [ServiceBehavior (InstanceContextMode = InstanceContextMode.Single)]

If you need behavior for only the same session, but not for all clients, you can mark it as a session with the following service behavior [ServiceBehavior (InstanceContextMode = InstanceContextMode.PerSession)]

Another option is for each call, which is the default option. [ServiceBehavior (InstanceContextMode = InstanceContextMode.PerCall)]

0
source

All Articles