就個人而言,數據庫選項聽起來像是矯枉過正,只是基於存儲當前用戶的概念。如果你實際存儲的不止這些,那麼使用數據庫可能是有道理的。但是,假設您只是想從WCF服務的兩個實例中獲取當前用戶的列表,我會使用內存中的解決方案,就像是一個靜態的通用字典。只要服務可以唯一標識,我就會使用唯一的服務ID作爲字典中的關鍵字,並將每個關鍵字與該服務的用戶名稱(或某些適當的用戶數據結構)的通用列表配對。例如:
private static Dictionary<Guid, List<string>> _currentUsers;
由於此字典將在兩個WCF服務之間共享,因此您需要同步對它的訪問。這是一個例子。
public class MyWCFService : IMyWCFService
{
private static Dictionary<Guid, List<string>> _currentUsers =
new Dictionary<Guid, List<string>>();
private void AddUser(Guid serviceID, string userName)
{
// Synchronize access to the collection via the SyncRoot property.
lock (((ICollection)_currentUsers).SyncRoot)
{
// Check if the service's ID has already been added.
if (!_currentUsers.ContainsKey(serviceID))
{
_currentUsers[serviceID] = new List<string>();
}
// Make sure to only store the user name once for each service.
if (!_currentUsers[serviceID].Contains(userName))
{
_currentUsers[serviceID].Add(userName);
}
}
}
private void RemoveUser(Guid serviceID, string userName)
{
// Synchronize access to the collection via the SyncRoot property.
lock (((ICollection)_currentUsers).SyncRoot)
{
// Check if the service's ID has already been added.
if (_currentUsers.ContainsKey(serviceID))
{
// See if the user name exists.
if (_currentUsers[serviceID].Contains(userName))
{
_currentUsers[serviceID].Remove(userName);
}
}
}
}
}
既然你不想特定服務列出兩次的用戶,它很可能是有意義與HashSet<string>
更換List<string>
。
試試這個答案:http://stackoverflow.com/questions/617256/best-way-to-share-session-state-type-data-between-two-net-applications – 2009-09-04 02:16:08