Wcf – ChannelFactory: creating and disposing

channelfactorywcf

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?

Best Answer

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();
    }       
}
Related Topic