WCFService从Windows服务调用Singleton实例返回空

时间:2017-01-19 12:43:06

标签: c# wcf

我有一个来自数据库的静态(大)数据,我需要发送给客户端,所以我创建了一个单例类,从数据库中获取数据并填充列表。 我在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));

1 个答案:

答案 0 :(得分:2)

我认为你错过了new Lazy<SalesHelper>(() => new SalesHelper());的初始化。 执行此操作_cache会导致SalesHelper.Instance.SetCache(_cacheSale); 未初始化。

所以我们有几个解决方法可供选择。 其中一个是启动Intance:

//_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));

它应该是这样的:

Intance

另一个是用工厂方法GetInstance()替换你的道具 String sql = "select m.menuid as menuid,m.parentid as parentid,m.menuname as menuname,m.url as url,m.status as status,m.usertype as usertype,m.isParent as isParent,m.childMenu as childMenu from Menu m join m.users u where u.userId = "+userid +""; q = session.createQuery(sql).setResultTransformer(Transformers.aliasToBean(Menu.class)); ,它应该接收缓存并在需要时设置它。

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