I often hear that WCF is hard to work with because it needs so much configuration. That might have been true in .Net 3.5, but since .Net 4.0 <serviceActivations>
has been around to make our lives easier. Today, .Net 4.0 is not far from the Stone Age… So I am surprised that this is still an issue.
To get started simply:
- Create empty ASP.Net Web Application
- Add reference to System.ServiceModel.dll
- Add the
<system.serviceModel>
tag from the snippet below in your Web.config
1 |
|
You now have a convenient way to host WCF services by adding references to all Class Libraries that contain your service implementations. To get the Service Hosting Environment to pick up your services, all you have to do is to point them out with an extra <add />
under <serviceActivations>
.
This approach has a number of advantages:
- The hosting code is close to zero, which makes it easy to reach 100% code coverage through unit testing.
- All services automatically gets endpoints over many protocols, which makes the information flow in your application more configurable.
- In addition to the service implementation, there is no need for metadata files just to make hosting possible.
Below is an example of a service implementation.
1 | using System; |
IoC
To make it easier to test the services that I write, I often use IoC containers of some sort to handle dependency resolution. The default ServiceHostFactory
does not let you configure the container.
To do this with Unity you can replace the factory with a UnityServiceHostFactory, which can be found in the NuGet-package Unity.Wcf.
Client Proxies
Please do not use WCF clients generated with Add ? Add Service Reference… They are hard to maintain and dispose of correctly.
One way to create a proxy to a WCF service is to inherit ClientBase<T>
. It works pretty well, except that someone at Microsoft must have made a mistake when implementing its Dispose functionality. Or more precise, its lack of. According to their recommendations; to be sure to close the proxy once you are done using it, the client code should be bloated with enormous try-catch blocks.
What is natural for me is to use using-blocks, but apparently this is not possible without some customization.
Custom Client Proxy
Out on the ?internet?, there exists many suggestions how to do this. What has been working for me is to use the following wrapper around the ClientBase<T>
.
1 | using System; |
With it you can either provide the client configuration in your App/Web.config like so:
1 |
|
Or inject it manually in the ServiceClient(Binding, EndpointAddress)
constructor.
How do you use prefer to use WCF clients?