“WCF服务不能用于通信,因为它处于故障状态”
我收到此错误的原因是因为我没有关闭与WCF服务的连接。一段时间后系统发出此错误。可能是当打开的连接太多时会出现错误。
public void CloseChannels()
{
bool success = false;
foreach (ChannelFactory li in factoryList)
{
try
{
if (li.State == CommunicationState.Opened)
li.Close();
li.ToString()));
success = true;
}
catch (Exception ex)
{
Helpers.Logger.Log.Error("Could not close connection for the service",ex);
}
finally
{
if (!success)
{
if (li.State == CommunicationState.Opened)
li.Abort();
}
}
}
}
我必须为每个服务调用调用此方法以确保连接已关闭。 ASP.NET MVC中是否存在全局位置,我可以在其中调用它? (例如,在ASP.NET Web表单中,我们有页面OnUnload事件)
答案 0 :(得分:2)
当我调用我的wcf方法时,我总是使用“using”,然后它会在完成后使用它关闭并处理它。
using (var client = new WCFServiceClient())
{
client.GetCountries();
}
答案 1 :(得分:1)
您有三种或更多种可能性来解决问题:
使用
无论何时使用服务,都要在使用块内进行。
using (var serviceClient = new ServiceClient())
{
serviceClient.DoSomething();
}
使用IDisposable接口(Controller实现它)
public override void Dispose()
{
_myServiceClient.Dispose();
}
使用依赖注入
使用依赖注入和生命周期管理器,使控制器和服务客户端的生命周期与http请求相同。