ChannelFactory:创建和处理

3

我编写了一个SDK,用于WPF客户端调用WCF服务和缓存。这些WCF服务是使用ChannelFactory调用的,因此我没有服务引用。为此,我创建了一个工厂来处理打开和关闭ChannelFactory和ClientChannel,如下所示:

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

我每次调用请求都像这样:

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

尽管这样可以工作,但因为每个请求都会打开和关闭客户端通道和工厂,所以速度较慢。如果保持打开状态,则速度非常快。但我想知道最佳实践是什么?我应该保持打开状态吗?还是不保持?如何正确处理这个问题?

可能是 https://dev59.com/kXNA5IYBdhLWcg3wrf83 的重复问题。 - Daniel Auger
可能是ChannelFactory.Close VS IClientChannel.Close的重复问题。 - TamaMcGlinn
1个回答

2

谢谢Daniel,我没有看到那篇文章。所以我想以下可能是一个好的方法:

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

推荐的方法是缓存通道工厂,但重新创建通道。 - mBardos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接