User Tools

Site Tools


technology:dotnet:wcf:clientusage

Wie verwende ich einen WCF Client

Aus http://stackoverflow.com/questions/1400010/closing-wcf-connection habe ich folgendes gelernt:

Clients nicht mit using erzeugen:

using(ClientProxy proxy = new ClientProxy())
{   
  //call your service methods
}

Begründet wird das wie folgt: “The 2nd sample using the “using” block is incorrect. The using block ensures that the Dispose method is called on the proxy object. The Dispose method in turn calls the Close method which will (try to) connect to the service which will throw an exception when the communication state is faulted.”

Stattdessen soll man folgendes machen:

YourClientProxy clientProxy = new YourClientProxy();

try
{
   .. use your service
   clientProxy.Close();
}
catch(FaultException)
{
   clientProxy.Abort();
}
catch(CommunicationException)
{
   clientProxy.Abort();
}
catch (TimeoutException)
{ 
   clientProxy.Abort();
}

Ich habe pro Client einen Proxy-Supplier mit zwei statischen Methoden gebaut, die einen Client erzeugen und ihn auch wieder schließen. Diese können nun von überall verwendet werden.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;

namespace ProMSchedulingClient.ProxyProviders
{
    public static class AddressServiceProvider
    {
        public static ProMLegacyAddressServiceReference.AddressServiceClient GetServiceClient()
        {
            return new ProMLegacyAddressServiceReference.AddressServiceClient("BasicHttpBinding_IAddressService", string.Format("http://{0}/ProMSchedulingServiceHost/AddressService", HostConfiguration.Url));
        }

        public static void CloseServiceClient(ProMLegacyAddressServiceReference.AddressServiceClient clientProxy)
        {
            try
            {
                if (clientProxy != null && clientProxy.State == CommunicationState.Opened) clientProxy.Close();
            }
            catch (FaultException)
            {
                clientProxy.Abort();
            }
            catch (CommunicationException)
            {
                clientProxy.Abort();
            }
            catch (TimeoutException)
            {
                clientProxy.Abort();
            }
            catch (Exception)
            {
                clientProxy.Abort();
                throw;
            }
        }
    }
}
technology/dotnet/wcf/clientusage.txt · Last modified: 2012/12/20 15:03 by rtavassoli