user609886
user609886

Reputation: 1669

Static Variables in WCF

I have some WCF services. These services run in ASP.NET. I want these services to be able to access a static variable. My problem is, I'm not sure where the appropriate server level storage mechanism is. I don't want to use the database because of speed. But, I want the static variables to stay in memory as long as possible. In fact, I'd like it to stay until I restart my server if it all possible.

Can anyone provide me with any ideas?

Upvotes: 8

Views: 13958

Answers (3)

WhiteKnight
WhiteKnight

Reputation: 5056

If all the services are in a single ServiceContract and if all the member variables in your service can be shared across all sessions, then you could set the ServiceBehavior to have a single instance.

[ServiceBehavior( InstanceContextMode = InstanceContextMode.Single )]
public class MyService : IMyServiceContract
{
}

Upvotes: 0

Bala R
Bala R

Reputation: 108957

You could have something like this

public static class StaticVariables
{
    private static string _variable1Key = "variable1";

    public static Object Variable1
    {
        get 
        {
            return Application[_variable1Key]; 
        }

        set 
        {
            Application[_variable1Key] = value; 
        }
    } 
}

The Application collection itself is thread safe but the stuff you add to it might not be; so keep that in mind.

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

You could use static variables in WCF but you must properly synchronize the access to them because they can potentially be accessed from multiple threads concurrently. The values stored in static variables are accessible from everywhere in the AppDomain and remain in memory until the server is restarted.

Upvotes: 15

Related Questions