【问题标题】:Async REST Services using WCF WebApi使用 WCF WebApi 的异步 REST 服务
【发布时间】:2012-02-15 14:21:00
【问题描述】:

我想知道各位开发者对 WCF WebApi 服务的看法。

在 N 层应用程序中,我们可以有多个服务层。我们可以让服务使用来自外部服务的数据。在这种情况下,使用 WCF 4.0 创建异步休息服务是值得的。

public interface IService
{
   [OperationContractAttribute(AsyncPattern = true)]
   IAsyncResult BeginGetStock(string code, AsyncCallback callback, object asyncState);
    //Note: There is no OperationContractAttribute for the end method.
    string EndGetStock(IAsyncResult result); 
}

但是随着 WCF WebApi 的发布,仍然需要这种方法吗?创建异步服务?

如何在 IIS/WAS/Self Hosting 中托管它们

期待建议和cmets。

【问题讨论】:

    标签: wcf wcf-rest wcf-web-api wcf-hosting


    【解决方案1】:

    WCF Web API 带有一个完全异步的 HttpClient 实现,您可以在 IIS 中托管,也可以完全使用 sefhost。

    对于异步 REST“服务”场景,请阅读“Slow REST

    【讨论】:

      【解决方案2】:


      那么我的感受,为了在最新的WCF WebAPIs(preview 6)中创建异步操作我仍然可以使用相同的模式(Begin/End),但是我也可以使用Task编程模型来创建异步操作,这很多更简单。

      下面显示了使用任务模型编写的异步操作的一个示例。

          [WebGet]
          public Task<Aggregate> Aggregation()
          {
              // Create an HttpClient (we could also reuse an existing one)
              HttpClient client = new HttpClient();
      
              // Submit GET requests for contacts and orders
              Task<List<Contact>> contactsTask = client.GetAsync(backendAddress + "/contacts").ContinueWith<Task<List<Contact>>>((responseTask) =>
                  {
                      return responseTask.Result.Content.ReadAsAsync<List<Contact>>();
                  }).Unwrap();
              Task<List<Order>> ordersTask = client.GetAsync(backendAddress + "/orders").ContinueWith<Task<List<Order>>>((responseTask) =>
                  {
                      return responseTask.Result.Content.ReadAsAsync<List<Order>>();
                  }).Unwrap();
      
              // Wait for both requests to complete
              return Task.Factory.ContinueWhenAll(new Task[] { contactsTask, ordersTask },
                  (completedTasks) =>
                  {
                      client.Dispose();
                      Aggregate aggregate = new Aggregate() 
                      { 
                          Contacts = contactsTask.Result,
                          Orders = ordersTask.Result
                      };
      
                      return aggregate;
                  });
          }
      
          [WebGet(UriTemplate = "contacts")]
          public Task<HttpResponseMessage> Contacts()
          {
              // Create an HttpClient (we could also reuse an existing one)
              HttpClient client = new HttpClient();
      
              // Submit GET requests for contacts and return task directly
              return client.GetAsync(backendAddress + "/contacts");
          }
      

      【讨论】:

        猜你喜欢
        • 2011-10-14
        • 1970-01-01
        • 2012-10-03
        • 2011-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多