WCF 调用 - 最佳做法

本文关键字:最佳 调用 WCF | 更新日期: 2023-09-27 18:37:11

这个问题的2个小部分,希望能为我澄清一些歧义。

首先,哪个更适合调用 WCF 服务?

using (var myService = new ServiceClient("httpBinding")){
     try{         
          var customerDetails = GetCustomerDetails();
          var results = myService.GetCustomerPurchases(customerDetails);
     }catch(Exception e){
          ......
     }
}

var myService = new ServiceClient("httpBinding");
try{
     var customerDetails = GetCustomerDetails();
     var results = myService.GetCustomerPurchases(customerDetails);
}catch(Exception e){
     .......
}

想知道的是,我应该始终将我的服务调用包装在使用块中吗?如果服务引发异常,是否会调用 IDisposable.Dispose() ?

WCF 调用 - 最佳做法

看看这个问题。

您也可以创建几个类,例如

public class ClientService<TProxy>
{
    private static ChannelFactory<TProxy> channelFactory = new ChannelFactory<TProxy>("*");
    public static void SendData(Action<TProxy> codeBlock)
    {
        var proxy = (IClientChannel) channelFactory.CreateChannel();
        bool success = false;
        try
        {
            codeBlock((TProxy)proxy);
            proxy.Close();
            success = true;
        }
        finally
        {
            if (!success)
            {
                proxy.Abort();
            }
        }
    }
    public static TResult GetData<TResult>(Func<TProxy, TResult> codeBlock)
    {
        var proxy = (IClientChannel) channelFactory.CreateChannel();
        bool success = false;
        TResult result;
        try
        {
            result = codeBlock((TProxy)proxy);
            proxy.Close();
            success = true;
        }
        finally
        {
            if (!success)
            {
                proxy.Abort();
            }
        }
        return result;
    }
}
public class SomeAnotherService<TProxy>
{
    public static bool SendData(Action<TProxy> codeBlock)
    {
        try
        {
            ClientService<TProxy>.SendData(codeBlock);
            return true;
        }
        catch(Exception ex)
        {
            //...
        }
        return false;
    }
    public static TResult GetData<TResult>(Func<TProxy, TResult> codeBlock)
    {
        TResult result = default(TResult);
        try
        {
            result = ClientService<TProxy>.GetData(codeBlock);
        }
        catch (Exception ex)
        {
            //...
        }
        return result;
    }
}

有时很方便。下面是调用某些服务方法的示例。

var someObj = SomeAnotherService<IMyService>.GetData(x => x.SomeMethod());

处理 WCF 代理时不要使用 using。原因之一是Dispose()将调用Close()如果代理处于Faulted状态,则会引发异常。所以最好的用途是这样的:

var myService = new ServiceClient("httpBinding");
try
{
    myService.SomeMethod();
}
catch
{
    // in case of exception, always call Abort*(
    myService.Abort();
    // handle the exception
    MessageBox.Show("error..");
}
finally
{
    myService.Close();
}