【问题标题】:WCFService calling a Singleton instance from windows service returning emptyWCFService 从 Windows 服务调用 Singleton 实例返回空
【发布时间】:2017-06-04 04:04:42
【问题描述】:

我有一个来自数据库的静态(大)数据,我需要发送给客户端,所以我创建了一个单例类,它从数据库中获取数据并填充列表。 我在windows服务里面启动了服务主机,所以当外部调用wcf数据为空时,我该怎么办?

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class CacheDataService : ICacheDataService
{
    public List<Sale> GetDataFromImobDateById(int idImob, DateTime date)
    {
        return SalesHelper.Instance.GetDataFromImobDate(idImob, date);
    }
}
public class SalesHelper
    {
        static Lazy<SalesHelper> singleton = new Lazy<SalesHelper>(() => new SalesHelper());
        public static SalesHelper Instance { get { return singleton.Value; } }
        ICacheData<Sale> _cache;
        List<Sale> CacheData = new List<Sale>();
        public void SetCache(ICacheData<Sale> cacheData)
        {
            _cache = cacheData;
        }
        public void ReloadCache()
        {
            CacheData.Clear();
            GetAllData();
        }
        public void GetAllData()
        {
            CacheData = _cache.GetAllData();
        }

        public List<Sale> GetDataFromImobDate(int idImob, DateTime date)
        {
            var result = (from r in CacheData
                          where r.Data_Alteracao.Equals(date)
                          && r.Id_Imobiliaria.Equals(idImob)
                          select r).ToList();
            return result;
        }
}

在服务中我启动 ServiceHost 和缓存

_tempSales = new SalesHelper();
ICacheData<Sale> _cacheSale = new Sale();
_tempSales.SetCache(_cacheSale);
_tempSales.GetAllData();
_service = new ServiceHost(typeof(CacheDataService));

【问题讨论】:

  • 能否也添加 SalesHelper 类?
  • 对不起,我输入了错误的类名。已经更正了。
  • 还有一个问题:你在哪里使用这个方法GetDataFromImobDateById?这就是数据为空的地方,对吧?我为什么这么问? _tempSales 正在使用其各自的缓存进行初始化,没关系。但是SalesHelper.Instance 从来没有设置过...
  • 来自我引用 wcf 的客户端。另外我不需要设置实例,对,它已经设置为_singleton的值

标签: c# wcf


【解决方案1】:

我认为您缺少SalesHelper.Instance 的初始化。 这样做new Lazy&lt;SalesHelper&gt;(() =&gt; new SalesHelper()); 会导致_cache 的实例未初始化。

所以我们有几个解决方法可供选择。 其中之一是初始化 Intance:

SalesHelper.Instance.SetCache(_cacheSale);

应该是这样的:

//_tempSales = new SalesHelper();
ICacheData<Sale> _cacheSale = new Sale();
//_tempSales.SetCache(_cacheSale);
//_tempSales.GetAllData();
SalesHelper.Instance.SetCache(_cacheSale);
SalesHelper.Instance.GetAllData(); //Now it should return the info
_service = new ServiceHost(typeof(CacheDataService));

另一个是用工厂方法 GetInstance() 替换你的 prop Intance,它应该接收缓存并在需要时设置它。

如果第一个解决方法可以解决您的问题,请告诉我。

【讨论】:

  • 哦,我现在正在测试,但这是有道理的。我所做的是完全错误的。
猜你喜欢
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-08
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
相关资源
最近更新 更多