現在、必要なたびにキャッシュし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;
}
}