Where to trap failed connection on WCF calling class?

后端 未结 7 1143
失恋的感觉
失恋的感觉 2021-01-13 05:09

I\'m trying to write a class that encapsulates WCF calls (the client is Silverlight, if it matters). It all works swimmingly, but I\'m not sure how to trap a connection fail

7条回答
  •  醉梦人生
    2021-01-13 05:36

    Am I right in thinking that you have designed your ServiceCaller class so that you can call it in a using block?

    If yes, then that's the problem. The WCF channel classes have been designed in such a way as to make it extremely difficult to write completely general disposing code that caters for all possible error conditions. If it were simple, then the channel classes themselves would be safe to dispose and you wouldn't need a wrapper class.

    The only safe way I have found to date is to encapsulate not the dispose logic, but the entire call sequence, thus:

    public static void Invoke(ChannelFactory factory, Action action) where TContract : class {
    
        var proxy = (IClientChannel) factory.CreateChannel();
        bool success = false;
        try {
            action((TContract) proxy);
            proxy.Close();
            success = true;
        } finally {
            if(!success) {
                proxy.Abort();
            }
        }
    }
    

    I know that's a synchronous call, but the principle is the same. Instead of you trying to deduce whether you should call Close or Abort, you determine it in advance based on how far through the call you managed to get before it fell over.

    Note - only the actual channel needs this special treatment. You can dispose of the factory any way you like AFAIK.

提交回复
热议问题