代码之家  ›  专栏  ›  技术社区  ›  L-Four

ChannelFactory:创建和处理

  •  3
  • L-Four  · 技术社区  · 14 年前

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

    1 回复  |  直到 11 年前
        1
  •  3
  •   L-Four    14 年前

    谢谢丹尼尔,没看到那个帖子。所以我想以下可能是一个很好的方法:

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