Skip to main content
 首页 » 编程设计

c#之WCF 服务在每次调用时实例化

2024年02月13日13开发

我在客户端有一个 WCF 服务,在服务器端有一个 wcf 服务。 每项服务都有这一行:

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)] 

我正在使用不安全的 basicHttpBinding。

我在客户端服务上有方法:

private static ChannelFactory<IDatabaseProvider> _channel; 
private static IDatabaseProvider _proxy; 
private static DataTransferClient _client; 
 
private bool IsChannelStateNeedToInit() 
{ 
        return _proxy == null || ((IClientChannel)_proxy).State == System.ServiceModel.CommunicationState.Faulted || ((IClientChannel)_proxy).State == System.ServiceModel.CommunicationState.Closed; 
} 
public bool ConnectService() 
{ 
        try 
        { 
            if (_channel == null || _proxy == null || IsChannelStateNeedToInit()) 
            { 
                _channel = new ChannelFactory<IDatabaseProvider>("DatabaseProviderEndpointClient"); 
                _proxy = _channel.CreateChannel(); 
                _proxy.ConnectService(); 
            } 
            return _proxy.IsDataBaseConnected();  
        } 
        catch (Exception ex) 
        { 
            Logger.Instance.LogFatal(ex); 
            return false;  
 
        } 
} 

我的客户端服务由windows服务托管,我的服务器服务由IIS7托管。 在(服务器的)wcf 服务的每个实例化中,我都会写入事件日志,并且我看到在每次调用时我的 WCF 服务都在实例化,即使 IsChannelStateNeedToInit() 返回 false。

在我的一个测试环境中,我什至在服务器端遇到了这个异常。

Failed to InsertBulkToDatabase. EXCEPTION: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. 

我的网络配置文件:

<serviceBehaviors> 
    <behavior name="DefaultServiceBehavior"> 
      <serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="200" maxConcurrentInstances="200"/> 
    </behavior> 
  </serviceBehaviors> 

我的应用配置

<basicHttpBinding> 
    <binding name="BasicHttpBindConfig" closeTimeout="00:10:00" openTimeout="00:10:00" 
      receiveTimeout="00:10:00" sendTimeout="00:10:00" hostNameComparisonMode="StrongWildcard" 
      maxBufferPoolSize="524288" maxBufferSize="6553600" maxReceivedMessageSize="6553600" 
      transferMode="Buffered"> 
      <security mode="None"> 
      </security> 
    </binding> 
  </basicHttpBinding> 

如何避免在每次调用时都进行这种类型的实例化? 为什么我的服务不只在不同的客户端上实例化?

请您参考如下方法:

basicHttpBinding 不支持 session 。这就是每次调用都会获得一个新实例的原因。请参阅:http://msdn.microsoft.com/en-us/library/ms731092(v=vs.110).aspx

您可以通过使用 [ServiceContract(SessionMode = SessionMode.Required)] 注释您的服务契约(Contract)来避免将来出现这种麻烦 如果您尝试在具有不支持 session 的绑定(bind)的端点中使用服务契约,将抛出异常