0

"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)

Dhanuka777
  • 8,331
  • 7
  • 70
  • 126

2 Answers2

2

When i call my wcf methods i always use "using" then it will close and dispose the object after its done using it.

        using (var client = new WCFServiceClient())
        {
            client.GetCountries();
        }
Tan
  • 2,148
  • 3
  • 33
  • 54
1

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.

TGlatzer
  • 5,815
  • 2
  • 25
  • 46
  • Actually I have picked a combination of 1st and 2nd options. In my "Service Factory" class, which creates all the services, I made it Disposable by implementing IDisposable interface, and called the close channel method inside that. – Dhanuka777 Dec 13 '13 at 09:45
  • I would prefer calling Dispose() on such objects, but that probably does not matter in the end. (In fact for `ClientBase` `Dispose()` calls `Close()`) – TGlatzer Dec 13 '13 at 10:18