English 中文(简体)
如何避免"服务通道"泄漏 当缓冲时 服务通道设施?
原标题:How to avoid ServiceChannel leak when caching ServiceChannelFactory?

目前我正在缓存 ServiceChanclefatory , 每次我需要时都会创建一个新的 ServiceChannel 。 我期望垃圾收集器会处置 ServiciceChannel 。 但是, 工厂会保存每个频道的引用, 以便当您调用 ServiciceFactoryChannel.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;
    }
}
问题回答

您可以使用自动/团结/注射等IoC容器,或者用于非常基本但快速的DyNAMOIOC。

设置您的容器时, 请仅提及服务通道设施 。 当您创建了 IService Channe( 服务 IMY Service) 时, 请同时注册 。

但要小心, 当您的 IServiceChanel 。 错误事件被击中时, 您需要关闭、 处置并重建它, 并将其添加到 IoC 容器中 。 这样, 只要呼叫者需要您的服务, 它就会处于无过失状态 。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签