就个人而言,数据库选项听起来像是矫枉过正,只是基于存储当前用户的概念。如果你实际存储的不止这些,那么使用数据库可能是有道理的。但是,假设您只是想从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