Search code examples
wcfasp.net-mvc-4wcf-binding

Where to close the WCF service connection in MVC


"WCF Service cannot be used for communication because it is in the Faulted state"

I got this error and reason is because I have not being closing my connections to WCF services. After a while system gives this error. May be when there are too many connections opened this gives the error.

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

I have to call this for each an every service call to make sure the connection is closed. Is there a global place in ASP.NET MVC, where I can call this? (e.g. In ASP.NET Web forms, we had page OnUnload event)


Solution

  • You have three or more possibilities to solve the Problem:

    Use using
    Whenever you are using a service do it inside a using block.

    using (var serviceClient = new ServiceClient())
    {
        serviceClient.DoSomething();    
    }
    

    Use the IDisposable interface (Controller implements it)

    public override void Dispose()
    {
        _myServiceClient.Dispose();
    }
    

    Use Dependency Injection
    Use dependency injection and a lifetime manager which makes the lifetime of the controller and service clients the same as the http-request.