首页 > 解决方案 > 什么是静态字典的生命周期 | 生活方式瞬态 | C# | WCF

问题描述

我将一些信息存储在静态字典中,该字典在 WCF 服务组件内部的类中定义,如下所示:

    public class UserAuthenticator : IUserAuthentication
    {                    

                public static ConcurrentDictionary<UserInfo, ConcurrentDictionary<string, BookingDetails>>BookingDetailsDictionary = new ConcurrentDictionary<UserInfo, ConcurrentDictionary<string, BookingDetails>>(new UserEqualityComparer());

                public static ConcurrentDictionary<string, Connector> connectorDictionary = new ConcurrentDictionary<string, Connector>();

      public BookingDetails Authenticate(UserInfo userInfo, ServiceDetails serviceDetail, XmlElement requestData)
            {
                var bookDetails = new BookingDetails();
                try
                {
                    ConcurrentDictionary<string, BookingDetails> dicObject = null;
                    if (bookingDictionary.TryGetValue(userInfo, out dicObject))
                    {...}
                    else 
                    {
                    //  call Database and get value from database and fill db value in to static ConcurrentDictionary
                    }
                }
            }
    }

在这里,我检查静态 ConcurrentDictionary 键,如果值不在字典中,然后调用数据库并在字典中填充值。

预期的输出是第一次调用 wcf 服务,然后调用数据库并在 ConcurrentDictionary 中填充值,然后在所有 WCF 服务调用之后从 ConcurrentDictionary 读取数据

现在,问题是有时我看到静态 ConcurrentDictionary 计数为零。奇怪的是应用程序池仍然处于活动状态。没有应用程序池被回收仍然随机调用数据库,有时它从 ConcurrentDictionary 获取数据

这对我来说真的很奇怪。我假设静态变量将保持其值,直到应用程序结束。但即使应用程序池没有回收或 IIS 没有重新启动,静态变量也会归零。

你有什么建议?使用 ConcurrentDictionary 变量是更好的选择吗?

注意:我在我的 wcf 应用程序中使用了城堡温莎依赖注入,并且UserAuthenticator类注册LifestyleTransient()如下

Component.For<IUserAuthentication, UserAuthenticator>().LifestyleTransient()

请告诉我最好的解决方案

提前致谢

标签: c#wcfstaticcastle-windsorconcurrentdictionary

解决方案


最后我得到了上述问题的解决方案

因为我ConcurrentDictionaryWCF项目中使用了静态,并且还为每个进程实现了网络花园和静态变量,所以它在网络花园的某个时候不能在另一个进程中工作

解决方案就像现在停止文园一样,它的工作正常,未来将通过网络园实现分布式缓存,如(Radis,NCache 等)

感谢@mjwills 和@Shantanu 提出宝贵意见


推荐阅读