Dynamically updating WCF endpoint addresses in WSDL meta data

Introduction

I have already written some blog articles about WCF and how flexible and extensible it is. A lot of WCF its internal components can be extended or replaced by custom, user developed implementations. Not surprisingly, we can also hook into the WSDL meta data generation.

Recently I was in a situation were I had to develop a self hosted WCF service, but I did not know the target hosting server(s) address(es) upfront and it was impossible for me to change the address in the app.config before deployment. Because WCF requires an absolute address for self hosted services, I had to use localhost. This works fine and gives no issues when calling the service from another computer, but it has one important drawback: WCF will use the localhost address in the generated WSDL meta data. In order to fix this, I created a custom WCF behavior.

IWsdlExportExtension

We can hook into the WSDL meta data generation by implementing the interface IWsdlExportExtension. This interface contains 2 methods: ExportContract and ExportEndpoint. If the class also implements IContractBehavior, the method ExportContract will be invoked by the WCF pipeline and vice versa for IEndpointBehavior and ExportEndpoint.

Because I only wanted to modify the endpoint addresses, I only had to implement the interface IEndpointBehavior and the method ExportContract. I wanted this also as a service behavior, so I also implemented the interface IServiceBehavior and I also extended the behavior from Attribute. This way, the behavior can be easily injected into the WCF pipeline by annotating the service implementation class with the behavior.

The modification itself is very simple; every occurrence of localhost in the endpoint addresses is replaced by the DNS name of the host machine.

With the behavior in place, the meta data now contains the DNS name instead of “localhost” in the endpoint addresses.

Conclusion

Of course creating the endpoints dynamically in code at runtime could also have solved this problem, but that would result in code that is not reusable and the WCF service programmer would have been responsible for the implementation. By developing this as a behavior, it is reusable across services.