ASP.NET客户端应用程序中的WCF ChannelFactory和Channel缓存

tuc*_*caz 6 performance wcf .net-3.0 channel channelfactory

我正在构建一系列将由多个应用程序使用的WCF服务.因此,我正在尝试定义一个公共库来访问WCF服务.

知道不同用户发出的每个服务请求应该使用一个不同的Channel我正在考虑缓存Channel per-request(HttpContext.Current.Items)并缓存ChannelFactory用于创建每个Application(HttpApplication.Items)的通道,因为我可以创建多个通道相同ChannelFactory.

但是,在关闭ChannelFactory和Channel时,我对这个缓存机制有疑问.

  1. 我是否需要在使用后,在请求结束时关闭Channel,或者当该请求的上下文死亡时,是否可以将其关闭(?)?
  2. 那么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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Mat*_*ttC 8

完成后,理想情况下关闭频道.这会将其放回到通道池中,以便其他工作线程可以使用它.

是的,通道工厂(昂贵的位)可以在应用程序的生命周期内保留.


更新

从.Net 4.5开始,工厂ChannelFactory Caching .NET 4.5有一个内置的缓存选项

  • 精确+1 - 缓存"昂贵"的部分 - ChannelFactory - 但是根据需要创建频道并尽早关闭/处置 (4认同)