ChannelFactory: creating and disposing

L-Four picture L-Four · Nov 6, 2010 · Viewed 8.5k times · Source

I have written an Sdk that is used by a WPF client, and takes care of calling WCF services and caching. These WCF services are called using the ChannelFactory, so I don't have service references. To do that, I created a factory that handles opening and closing ChannelFactory and ClientChannel as follows:

public class ProjectStudioServiceFactory : IDisposable
{
    private IProjectStudioService _projectStudioService;
    private static ChannelFactory<IProjectStudioService> _channelFactory;

    public IProjectStudioService Instance
    {
        get
        {
            if (_channelFactory==null) _channelFactory = new ChannelFactory<IProjectStudioService>("ProjectStudioServiceEndPoint");
            _projectStudioService = _channelFactory.CreateChannel();
            ((IClientChannel)_projectStudioService).Open();                
            return _projectStudioService;
        }
    }

    public void Dispose()
    {
        ((IClientChannel)_projectStudioService).Close();
        _channelFactory.Close();
    }       
}

And each request I call like:

 using (var projectStudioService = new ProjectStudioServiceFactory())
        {
            return projectStudioService.Instance.FindAllCities(new FindAllCitiesRequest()).Cities;
        }

Although this works, it's slow because for every request the client channel and factory is opened and closed. If I keep it open, it's very fast. But I was wondering what the best practise would be? Should I keep it open? Or not? How to handle this in a correct way?

Answer

L-Four picture L-Four · Nov 6, 2010

Thanks Daniel, didn't see that post. So I guess that the following may be a good approach:

public class ProjectStudioServiceFactory : IDisposable
{
    private static IProjectStudioService _projectStudioService;
    private static ChannelFactory<IProjectStudioService> _channelFactory;

    public IProjectStudioService Instance
    {
        get
        {
            if (_projectStudioService == null)
            {
                _channelFactory = new ChannelFactory<IProjectStudioService>("ProjectStudioServiceEndPoint");
                _projectStudioService = _channelFactory.CreateChannel();
               ((IClientChannel)_projectStudioService).Open(); 
            }                               
            return _projectStudioService;
        }
    }

    public void Dispose()
    {
        //((IClientChannel)_projectStudioService).Close();
        //_channelFactory.Close();
    }       
}