目前我缓存并在每次需要时ServiceChannelFactory
创建一个新的。ServiceChannel
我预计ServiceChannels
垃圾收集器会处理它。但是,工厂会保留对每个通道的引用,以便在您调用时关闭通道ServiceFactoryChannel.Close()
。这导致许多旧渠道一直活跃,直到一切都停止工作。
我怎样才能缓存工厂并且仍然让垃圾收集器处理我的频道?
我的代码如下所示:
public class ServiceChannel
{
// Returns a ServiceChannel
public static TService Get<TService>()
{
var factory = GetChannelFactory<TService>();
string url = GetEndpoint<TService>();
var endPoint = new EndpointAddress(url);
return factory.CreateChannel(endPoint);
}
// Returns a ServiceChannelFactory, preferably from the cache
public static ChannelFactory<TService> GetChannelFactory<TService>()
{
var cacheKey = string.Format("MyProduct.Library.ServiceChannel.GetChannelFactory<{0}>()", typeof(TService));
var cache = HttpRuntime.Cache;
var factory = cache[cacheKey] as ChannelFactory<TService>;
if (factory == null)
{
factory = GetChannelFactoryUncached<TService>();
cache.Insert(cacheKey, factory);
}
return factory;
}
}