Home
Manage Your Code
Snippet: Generic Method For Accessing A Non-Faulted WCF Service Proxy (C#)
Title: Generic Method For Accessing A Non-Faulted WCF Service Proxy Language: C#
Description: A generic method for ensuring that a WCF service is accessed in a non-faulted CommunicationState state. Views: 185
Author: Bin Chen Date Added: 3/31/2008
Copy Code  
1using System.Diagnostics;
2using System.ServiceModel;
3
4
5/// <summary>
6/// Ensures the WCF service is returned in a non-faulted <see cref="CommunicationState"/>.
7/// </summary>
8/// <typeparam name="TInterface">The type of the interface.</typeparam>
9/// <typeparam name="TClass">The type of the class.</typeparam>
10/// <param name="service">An interface to the service in an unknown <see cref="CommunicationState"/>.</param>
11/// <returns>An interface to the service in a non-faulted <see cref="CommunicationState"/>.</returns>
12/// <remarks>
13/// If there was a previous error that resulted in a proxy being faulted this takes care of 
14/// closing it and recreating it so that it is ready for use on the next valid call.
15/// If the proxy is not faulted it returns it as is, in either a <see cref="CommunicationState.Created"/> or <see cref="CommunicationState.Opened"/> state.
16/// </remarks>
17private static TInterface GetNonFaultedService<TInterface, TClass>(TInterface service)
18    where TInterface : class
19    where TClass : ClientBase<TInterface>, TInterface, new()
20{
21    TInterface result = service;
22    TClass client = service as TClass;
23    
24    if (client.State == CommunicationState.Faulted)
25    {
26        // Close it
27        client.Abort();
28        
29        // Recreate it
30        result = new TClass();                
31        
32        // Check
33        client = result as TClass;
34        Debug.Assert(
35            client.State != CommunicationState.Faulted,
36            String.Format("Unexpectedly in {0} state after new creation.", client.State)
37        );
38    }
39
40    return result;
41}
42
Usage
IMyService myService = GetNonFaultedService(myService);