1

目前我缓存并在每次需要时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;
    }
}
4

1 回答 1

1

你可以使用像 Autofac/Unity/Ninject 这样的 IoC 容器,或者对于一个非常基本但快速的容器,使用 DynamoIOC。

设置容器时,对 ServiceChannelFactory 有一个引用。当您创建一个 IServiceChannel(到您的服务 IMyService)时,也要注册它。

但要小心,当您的 IServiceChannel.Faulted 事件被触发时,您需要关闭、处置并重新创建它,并将其添加回 IoC 容器中。这样,每当调用者需要访问您的服务时,它将处于非故障状态。

于 2012-05-24T14:22:24.820 回答