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