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!
tucaz
source share