在WCF中创建新ChannelFactory并重新打开wcf频道的成本

时间:2013-08-04 09:29:47

标签: c# wcf channelfactory

我在托管应用程序中使用WCF infra 我有客户端的包装类,如下所示:

public class ServiceClient<TService> 
    where TService : class
{
    private TService _channel;
    private ChannelFactory<TService> _channelFactory;
    private readonly object _syncLock = new object();
    private readonly Binding _binding;
    private readonly string _uri;

//I have sets of constructors, i get the endpoint and binding type for each client in constructing.

    public TService Channel { get { Initiliaze(); return _channel;  } }

    private void Initiliaze()
    {
        lock (_syncLock)
        {
            if (_channel != null) return;

            //Create channel factory with binding and address
            _channelFactory = new ChannelFactory<TService>(_binding,_uri);

            //add additional behaviors if they exist
            if (_applyDefaultBehavior)
            {
                _channelFactory.Endpoint.Behaviors.Add(new ClientEndpointBehavior<TService>(_container));
            }

            //register client on channel events
            _channelFactory.Opened += OnChannelFactoryOpened;
            _channelFactory.Closed += OnChannelFactoryClosed;
            _channelFactory.Faulted += OnChannelFactoryFaulted;

            _channel = _channelFactory.CreateChannel(); 
        }
    }

剩下的就是Dispose,现在它不那么重要了。

到目前为止,当我使用ServiceClient时 - 我没有使用(.. ServiceClient ...)但我没有打开/关闭WCF频道。

我正在处理的问题,我需要在每次调用时打开/关闭通道,我不想在每次调用时重新创建整个ServiceClient包装器,因为使用这些绑定创建ChannelFactory的成本。我只想打开。关闭频道。

我可以这样做:

((IChannel)_channel).Close();
((IChannel)_channel).Open();

每次手术前?或者我需要这样做:

((IChannel)_channel).Close();
_channel = _channelFactory.CreateChannel(); 

为了重新创建频道?
我认为最好的解决方案是在我的包装器中创建一个公共函数作为https://stackoverflow.com/a/573877/1426106

中的示例

0 个答案:

没有答案