开发者

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 varia开发者_高级运维bles 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?


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.


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.


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
{
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜