.NET and me Coding dreams since 1998!

21Jan/120

What is new in WCF in .NET 4.5 – Task and async

.NET 4.5 WCF – unit testable out of the box

As I mentioned already in How to get testable WCF code in simplest way? problem with abstracting WCF services occur due to the fact that the service contract is by definition not containing the async members defined and every solution I’ve seen enabling asynchronous calls to a WCF service adds a certain level of complexity to the code base so therefore I have chosen to use service generated proxy enhanced with some T4 magic creating appropriate interfaces.

I am happy to report that is not true any more and that

WCF in .NET 4.5 enables VERY easy asynchronous service calls in a testable manner out of the box.

Here’s a source code of the simplest illustration of what is the point. Usual constraints: works-for-me and take-it-as-an-idea-only.

In case all this async, Task<T> C# 5.0 things are new for you I suggest checking out some of presentations from my TPL delicious stack (especially “Future Directions For C#…” one there)

Server side code

Let’s stick to the simplest possible sample of a vanilla WCF service having a single operation returning a server time

using System;
using System.ServiceModel;
using System.Threading.Tasks;

namespace WcfService1
{
    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        Task<DateTime> GetServerTimeAsync();
    }
}

As you can notice there are two interesting moments in the contact definition:

  • Returning type is not DateTime - it is Task<DateTime>
  • The name of the operation ends with Async which is a naming convention for marking new C# 5.0 async methods

Implementation of the service contract is equally trivial:

using System;
using System.Threading.Tasks;

namespace WcfService1
{
    public class TestService : ITestService
    {
        public async Task<DateTime> GetServerTimeAsync()
        {
            return DateTime.Now;
        }
    }
}

Implementation has three key moments:

  • Method name ends with Async
  • It returns Task<DateTime>
  • method has a async keyword which allows me to write a simple method body like I would do it normally and return a simple date time and completely forget about Task<T>

In other words, thanks to C# 5.0 all I have to do is to replace DateTime with async task<DateTime> and everything else stays the same – AWESOME!.

Client side code

I am going to add to the solution simple console application and create a trivial service client file

using System;
using System.ServiceModel;
using System.Threading.Tasks;
using WcfService1;

namespace ConsoleApplication1
{
    public class TestServiceClient : ClientBase<ITestService>, ITestService
    {
        public Task<DateTime> GetServerTimeAsync()
        {
            return Channel.GetServerTimeAsync();
        }
    }
}

No magic here: using shared service library I get the service contract on client and use it in combination with ClientBase<T> to create a simple class wrapper implementing via delegation service contract.

Now the class which simulates the one performing a wcf service call in its implementation

using System;
using System.Threading.Tasks;
using WcfService1;

namespace ConsoleApplication1
{
    public class ServerTimeReader
    {
        private readonly ITestService testService;

        public ServerTimeReader(ITestService testService)
        {
            this.testService = testService;
        }

        public async Task<DateTime> GetTimeAsync()
        {
            return await this.testService.GetServerTimeAsync();
        }
    }
}

The ServerTimeReader has a ITestService based dependency injected through its constructor. It has a method called GetTimeAsync which awaits the async wcf service call to be finished. All the mumbo jumbo of AMP, events etc. in a single keyword – brilliant.

Now when we have a class invoking a WCF call let’s ramp up IoC container and make a async call to server using the code we wrote so far.

using System;
using Microsoft.Practices.Unity;
using WcfService1;

namespace ConsoleApplication1
{
    class Program
    {
        private static UnityContainer container;

        static void Main(string[] args)
        {
            container = new UnityContainer();
            container.RegisterType<ITestService, TestService>();

            ReadTime();

            Console.ReadLine();
        }

        private static async void ReadTime()
        {
            var serverTimeReader = container.Resolve<ServerTimeReader>();
            var serverTime = await serverTimeReader.GetTimeAsync();

            Console.WriteLine("Server time:" + serverTime);
        }
    }
}

It's a console app so the entry point is static Main method which creates a new instance of IoC container (Unity in this sample) and adds to the IoC container mapping of the server side service contract with the service client I wrote

Then client calls a ReadTime method which uses IoC container to resolve ServerTimeReader instance injecting to it during that resolution a service client instance. Then the code awaits the GetTimeAsync method which awaits the service client call which results with a asynchronous call to a server being made and awaited on client.

Once the server returns the result to client the client shows it in console – that’s it.

image

Conclusion

The simplicity of the code performing fully async call to a WCF service is so brilliant that I am not going to write unit test here for the GetTimeAsync method because it should be quite obvious how to do that. The code is almost the same as it would be if it was written for sync WCF calls and to learn just how to tacklethe TPL/async specific things check out this stack overflow page recommended by my friend Slobodan Pavkov

That’s it folks – hope this will be useful to someone!

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.