Windows Communication Foundation (WCF) is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments.
In order to communicate with a WCF service you will need a client proxy which can be generated automatically using Visual Studio by “Add Service Reference” but I don’t prefer this way because it generates too much code, extra configuration and the service must publish its metadata, besides that every time the service updated you will need to update the service reference in order to reflect the new changes.
To perfectly loose-couple your application layers you will need to separate service contracts into their own assemblies so they can be shared and consumed by different applications and layers but this approach leaves a lot of manual work for the clients consuming our services as each client has to implement proxy for the corresponding contract.
Through this talk I will show you a simple way to eliminate manual work during proxy development. I will use T4 to dynamically create proxy class for WCF service contract in the same assembly with the contract in order to simplify consumption of our WCF service. Finally in the talk I will show you how to create Visual Studio template to generate WCF proxy classes.
Before digging into WCF proxy generation, let’s have a look to how T4 works. T4 text template is a mixture of text blocks and control logic that can generate a text file. The control logic is written as fragments of program code in Visual C# or Visual Basic. The generated file can be text of any kind, such as a Web page, or a resource file, or program source code in any language.
The first thing we would do is to add T4 file to our solution, To do this, in Solution Explorer, right-click your project and point to Add, and then click New Item. In the Add New Item dialog box select Text Template from the Templates pane. Name the file NewTemplate.tt. Notice that the Custom Tool property of the file is TextTemplatingFileGenerator.
Open the added file and change “hostspecific” to true, “debug” to true, “language” to C# and the output extension to “cs” like below:
<#@ template language="C#" hostspecific="True" debug="True" #>
<#@ output extension="cs" #>
This means that our generated file will be in C# code and we enabled “hostspecific” in order to allow our T4 to access the text template host engine. Make sure that “System.ServiceModel” DLL is referenced. In T4 add the below directives:
<#@ Assembly Name="EnvDTE" #>
<#@ Assembly Name="EnvDTE80" #>
<#@ import namespace="EnvDTE" #>
<#@ Import Namespace="EnvDTE80" #>
<#@ Import Namespace="Microsoft.VisualStudio.TextTemplating" #>
The above directives allow us to reference and access to visual studio environment along with text template generation engine. I have created a utility helper class (WCFProxyGenerator) that will provide the necessary helper functions to create proxy, these functions are summarized below:
1- RootNamespace: Gets the root namespace of the target project.
2- DefaultNamespace: Gets the default namespace for the target project.
3- GetServiceInterface(): Gets service interface type object for the specified file (searches the file for WCF interfaces).
4- GenerateParameters(): Gets a string that contains WCF method parameters.
5- GenerateCodeImports(): Gets the namespaces that need to be imported by the proxy.
Let’s now write some real T4 code, the first thing we need here is the name of the WCF service contract file, so I will declare T4 variable for it, also we can give our user the chance to choose the name of the proxy, if the user does not provide a certain name for the proxy then we will use the same name of the T4 file:
string WCFServiceInterfaceFile = "wcfservicecontract.cs";
string ProxyName = "";
WCFProxyGenerator Context = new WCFProxyGenerator(this.Host);
CodeInterface2 ServiceContract = Context.GetServiceInterface(WCFServiceInterfaceFile);
if (ServiceContract != null)
ProxyName = System.IO.Path.GetFileNameWithoutExtension(this.Host.TemplateFile);
The above T4 code will create object of our utility class, then it will use that object to search for specified file in solution, if the contract is found then we will use utility object to import the required namespaces for our proxy “using statements”.
The next step is to write the T4 script that will generate WCF proxy class:
namespace <#=Context.DefaultNamespace #>
public partial class <#=ProxyName #> : ClientBase<<#=ServiceContract.Name #>>, <#=ServiceContract.Name #>
foreach (var itm in ServiceContract.Members)
if (itm is CodeFunction2)
CodeFunction2 method = (CodeFunction2)itm;
if (Context.IsServiceMethod(method) && method.Access == vsCMAccess.vsCMAccessPublic)
public <#=method.Type.AsString #> <#=method.Name #>(<#=Context.GenerateParameters(method.Parameters)#>)
<#=method.Type.TypeKind == vsCMTypeRef.vsCMTypeRefVoid ? "" : "return" #> this.Channel.<#=method.Name #>(<#=Context.GenerateParameters(method.Parameters, false) #>);
In the above script, we first declare the namespace of our class then we generate partial class for the proxy that implements “ClientBase<>” along with our WCF service interface. I used a partial class in order to give other developer space for extending proxy implementation.
The T4 script then loops through each method in the WCF service contract and checks if the method is WCF operation method and if so it generates the method signature by using our utility class. After generating the method signature we fill the method body by using the channel factory that we have from our inherited base class.
I created a Visual Studio item template in order to simplify our proxy generation process. You can download the item template here (WCFProxyGenerator.zip (208.85 kb)) then drop this zip file as is in the appropriate location to be used by visual studio, the default location for this file should be “%USERPROFILE%\Documents\Visual Studio 2010.\Templates\ItemTemplates\”, restart visual studio and create a new class library project then add a new item to the project (you should see our item template there):
Add the WCF proxy generator template file, create any WCF service contract and open the T4 file and pass the service contract file name to T4 file then save the T4 file and you will get your WCF proxy class generated.