The Inquisitive Coder – Davy Brion's Blog

Trying to walk that thin line between intelligence and ignorance

The Service Call Batcher

Posted by Davy Brion on June 28th, 2008

Picking up where we left off with the WCF batching… We had the following code client-side to execute a few service methods with one request:

            var results = service.Process(new GetProductCategoriesRequest(), new GetProductOverviewsRequest());

            View.ProductCategories = ((GetProductCategoriesResponse)results[0]).ProductCategories;

            View.Products = ((GetProductOverviewsResponse)results[1]).Products;

Similar to my query batcher, i wrote this simple WCFCallBatcher class:

    public class ServiceCallBatcher

    {

        private readonly IService service;

        private readonly Dictionary<string, int> responsePositions = new Dictionary<string, int>();

        private readonly List<Request> requests = new List<Request>();

        private Response[] responses;

 

        public ServiceCallBatcher(IService service)

        {

            this.service = service;

        }

 

        public void Add(string key, Request request)

        {

            requests.Add(request);

            responsePositions.Add(key, requests.Count - 1);

        }

 

        public T Get<T>(string key) where T : Response

        {

            if (responses == null) ExecuteRequests();

            return (T)responses[responsePositions[key]];

        }

 

        private void ExecuteRequests()

        {

            responses = service.Process(requests.ToArray());

        }

    }

and now we can rewrite the client code like this:

            var batcher = new ServiceCallBatcher(service);

            batcher.Add("categories", new GetProductCategoriesRequest());

            batcher.Add("products", new GetProductOverviewsRequest());

            View.ProductCategories = batcher.Get<GetProductCategoriesResponse>("categories").ProductCategories;

            View.Products = batcher.Get<GetProductOverviewsResponse>("products").Products;

Yes, we’ve got more lines of code now, but i like this block of a code a lot more than the earlier one. This is much more readable.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>