WCF ChannelFactory and Channel Caching in ASP.NET Client Application

I am creating a series of WCF services that will be used by more than one application. Because of this, I am trying to define a shared library for accessing WCF services.

Knowing that each service request made by different users must use a different channel. I think the cache uses the channel for the request ( HttpContext.Current.Items ) and caches the ChannelFactory used to create the channel for each application ( HttpApplication.Items ), since I can create several channels with the same ChannelFactory .

However, I have a question regarding this caching mechanism when it comes to closing ChannelFactory and Channel.

  • Is it necessary to close the Channel after using it at the end of the request, or is it normal to leave it closed there (?) When the continuation of this request dies?
  • What about ChannelFactory? Since each channel is associated with the ChannelFactory that created it, is it safe to maintain the same ChannelFactory throughout the application process (AppDomain)?

This is the code I use to manage this:

 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; } } } 

Thanks!

+6
source share
2 answers

It’s ideal to close the channel as soon as you are done with it. This will put it back in the channel pool so it can be used by another workflow.

Yes, the factory channel (expensive bit) can remain for the lifetime of the application.


Update

.Net 4.5 has built-in caching options for ChannelFactory Caching.NET 4.5 factories

+8
source

It is on the sidelines. Why are you using SessionID as a context key? The context.Items object is unique to each request. I.e:

 HttpContext.Current.Items[HttpContext.Current.Session.SessionID +"_ListOfOpenedChannels"] 

should be functionally equivalent to:

 HttpContext.Current.Items["ListOfOpenedChannels"] 
+1
source

All Articles