【发布时间】:2010-12-22 00:15:57
【问题描述】:
我正在构建一系列将被多个应用程序使用的 WCF 服务。因此,我正在尝试定义一个通用库来访问 WCF 服务。
知道不同用户发出的每个服务请求都应该使用不同的通道,我正在考虑缓存每个请求的通道 (HttpContext.Current.Items) 并缓存用于为每个应用程序创建通道的 ChannelFactory (HttpApplication.Items),因为我可以使用相同的ChannelFactory 创建多个频道。
但是,在关闭 ChannelFactory 和 Channel 时,我对这种缓存机制有疑问。
- 我是否需要在使用通道后、请求结束时关闭通道,或者当请求的上下文终止时是否可以将通道关闭 (?)?
- ChannelFactory 怎么样?由于每个通道都与创建它的 ChannelFactory 相关联,因此在应用程序进程 (AppDomain) 的生命周期内保持相同的 ChannelFactory 是否安全?
这是我用来管理这个的代码:
public class ServiceFactory
{
private static Dictionary<string, object> ListOfOpenedChannels
{
get
{
if (null == HttpContext.Current.Items[HttpContext.Current.Session.SessionID + "_ListOfOpenedChannels"])
{
HttpContext.Current.Items[HttpContext.Current.Session.SessionID + "_ListOfOpenedChannels"] = new Dictionary<string, object>();
}
return (Dictionary<string, object>)HttpContext.Current.Items[HttpContext.Current.Session.SessionID + "_ListOfOpenedChannels"];
}
set
{
HttpContext.Current.Items[HttpContext.Current.Session.SessionID + "_ListOfOpenedChannels"] = value;
}
}
public static T CreateServiceChannel<T>()
{
string key = typeof(T).Name;
if (ListOfOpenedChannels.ContainsKey(key))
{
return (T)ListOfOpenedChannels[key];
}
else
{
ChannelFactory<T> channelF = new ChannelFactory<T>("IUsuarioService");
T channel = channelF.CreateChannel();
ListOfOpenedChannels.Add(key, channel);
return channel;
}
}
}
谢谢!
【问题讨论】:
标签: performance wcf channel channelfactory .net-3.0