2011-07-27 14 views
1

RESTベースのサービスに対して非同期操作をサポートするプロキシクラスを作成したいとします。議論の便宜上WCFと非同期にRESTベースのサービスを使用するにはどうすればよいですか?

、のは、私はサービス、IServiceとしましょう:私は簡単に同期プロキシクラスを作成することができています

[ServiceContract] 
public interface IService 
{ 
    [OperationContract] 
    [WebGet(UriTemplate = "{a}/{b}")] 
    void Action(string a, string b); 
} 

を:

class Client: ClientBase<IService>, IService 
{ 
    public void Action(string a, string b) 
    { 
     Channel.Action(a, b); 
    } 
} 

(この技術はからですこのarticle

プロキシに非同期操作をサポートする同様の方法がありますか(BeginAction/EndActionまたはActionAsyncパターン)?または手動で自分自身をロールバックするベストプラクティスですか?

利用可能なメタデータがないため、Visual Studioでサービス参照を追加できません。

答えて

3

オペレーションコントラクトを対応する開始/終了ペアに置き換えると、それはRESTベースのコントラクトでも機能するはずです。 クライアントでの操作の同期と非同期バージョンの両方をにすることもできます(ただし、この場合、同期バージョンにのみ[WebGet]属性が必要です)。

public class StackOverflow_6846215 
{ 
    [ServiceContract(Name = "ITest")] 
    public interface ITest 
    { 
     [OperationContract] 
     [WebGet] 
     int Add(int x, int y); 
    } 
    [ServiceContract(Name = "ITest")] 
    public interface ITestClient 
    { 
     [OperationContract(AsyncPattern = true)] 
     IAsyncResult BeginAdd(int x, int y, AsyncCallback callback, object state); 
     int EndAdd(IAsyncResult asyncResult); 

     [OperationContract] 
     [WebGet] 
     int Add(int x, int y); 
    } 
    public class Client : ClientBase<ITestClient>, ITestClient 
    { 
     public Client(string baseAddress) 
      :base(new WebHttpBinding(), new EndpointAddress(baseAddress)) 
     { 
      this.Endpoint.Behaviors.Add(new WebHttpBehavior()); 
     } 

     public IAsyncResult BeginAdd(int x, int y, AsyncCallback callback, object state) 
     { 
      return this.Channel.BeginAdd(x, y, callback, state); 
     } 

     public int EndAdd(IAsyncResult asyncResult) 
     { 
      return this.Channel.EndAdd(asyncResult); 
     } 

     public int Add(int x, int y) 
     { 
      return this.Channel.Add(x, y); 
     } 
    } 
    public class Service : ITest 
    { 
     public int Add(int x, int y) 
     { 
      return x + y; 
     } 
    } 
    public static void Test() 
    { 
     string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; 
     WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress)); 
     host.Open(); 
     Console.WriteLine("Host opened"); 

     Client client = new Client(baseAddress); 
     Console.WriteLine("Sync result: {0}", client.Add(66, 77)); 
     client.BeginAdd(44, 55, delegate(IAsyncResult ar) 
     { 
      int result = client.EndAdd(ar); 
      Console.WriteLine("Async result: {0}", result); 
     }, null); 

     Console.WriteLine("Press ENTER to close the host"); 
     Console.ReadLine(); 
     host.Close(); 
    } 
} 
+0

ありがとう、これは私が探していたものです。私は自分自身をロールしていない嬉しい:)。 – jglouie