Search code examples
wcfwcf-restwcf-web-apiwcf-hosting

Async REST Services using WCF WebApi


I want to know what is the opinion of you fellow Developers regarding WCF WebApi services.

In an N-tier application we can have multiple layers of services. We can have services consuming data from external services. In that scenario its worth to create Async Rest Services using 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); 
}

But with the release of WCF WebApi this approach is still required? to create async services?

How to host them in IIS/WAS/Self Hosting

looking forward for suggestion and comments.


Solution


  • Well What i feel,In order to create asynchronous operations in the latest WCF WebAPIs (preview 6) I can still use same pattern (Begin/End), but I can also use the Task programming model to create asynchronous operations, which is a lot simpler.

    One example of an asynchronous operation written using the task model is shown below.

        [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");
        }