This post is part of a series about WCF extensibility points. For a list of all previous posts and planned future ones, go to the index page.
Continuing on the theme of metadata extensibility, this post is the logical counterpart of the previous one – while that covered hooking on the WSDL export code path, this one shows how we can intercept (and change) the WSDL import process, where one of the WCF tools (such as svcutil or the WsdlImporter class) takes the WSDL produced by a WCF or a 3rd-party service and generates a client which is able to talk to it.
Metadata isn’t one area in WCF which I haven’t worked much, and as I was researching for this post, I ran into two new extensibility points which I hadn’t heard about: IOperationContractGenerationExtension and IServiceContractGenerationExtension – I already updated the index page to add those two (this was actually one of my goals when I started writing this series – learn more about the product I work on, and it’s been quite educative for myself). They really are very much related to the WSDL import extension (you see something in the WSDL which you want to act upon, then you use those generation extensions to alter the code generation to deal with that new information). The example in the official samples (WSDL Documentation) uses this, and the example I have here also uses the same method. So I’m combining those three extensibility points in this single post.
Before any WCF-specific object is created based on the service metadata, BeforeImport is called to let the extension work with the service description objects (from the WSDL namespace), XML schemas and any policy assertions made in the WSDL. Notice that none of those parameters are WCF-related: the wsdlDocuments parameter is of type System.Web.Services.Description.ServiceDescriptionCollection (in the System.Web.Services.dll), and the other two parameters are from System.Xml.dll (System.Xml.Schema.XmlSchemaSet and ICollection of System.Xml.XmlElement), so this is called really before WCF has had any chance to look at the metadata.
After WCF has a chance to initialize its objects, then ImportContract is called so the user has a chance to modify the contract or insert other generation behaviors such as IOperationContractGenerationExtension and IServiceContractGenerationExtension for each contract found in the WSDL (each <wsdl:portType> element). ImportEndpoint is called for each endpoint which is found in the WSDL (corresponding to <wsdl:services>/<wsdl:port> elements). The parameters for the two methods are similar: the instance of the WsdlImporter class, and a conversion context which contains references to both the WCF objects relative to the operation (e.g., the ContractDescription for ImportContract) and the correspondent WSDL objects (e.g., the WSDL PortType for ImportContract). The order of the call of those two operations is not defined, so you shouldn’t depend on it.
Both IOperationContractGenerationExtension and IServiceContractGenerationExtension interfaces are simple, with one method with a single parameter with the context for the operation. For the operation contract generation extension, the parameter to GenerateOperation is an object with references to the ServiceContractGenerator which is being used to generate the client, as well as information relative to the operation itself: the operation description, and various System.CodeDom objects representing the operation itself. For the service contract generation extension, the parameter to GenerateContract is an object with references to the same ServiceContractGenerator, and information about the contract as a whole: the contract description, and CodeDom objects for the generated contract and callback contract (in case of duplex contracts), and the list of all operations in the contract.
There are no public implementations of the contract generation extensions in WCF. In most of the scenarios I’ve seen, those classes are implemented as internal classes, added to the service description during the service import via some WSDL import extension. There are some public implementations of IWsdlImportExtension, which define the default behavior of WCF metadata import for various components (transport, context and message encoding binding elements, standard binding and message contract), which you can derive from and override some of the default behaviors.
WSDL import extensions are typically used in conjunction with some tool such as svcutil. Since we can’t change the code from that tool, we can use configuration to add any extensions we define. The example below shows how a class which implements IWsdlImportExtension, called WsdlImportExtension (on namespace ImportNonReferencedTypes, in the ImportNonReferencedTypes assembly) is added to the list of extensions used by the WSDL importer used by the code. If we’re using svcutil, then this block of configuration would go into svcutil.exe.config.
It’s worth noting that if we’re generating the client directly (using MetadataExchangeClient, ServiceContractGenerator and WsdlImporter themselves) we can add the extension via code (using the WsdlImportExtensions property of the WsdlImporter class), but the configuration route is more often used because it can be used with tools such as svcutil as well.
Similar to the WSDL export extension, service (and operation) contract generator extensions need to be added as contract (and operation) behaviors to the description. The implementation of the methods for the I[Operation/Contract]Behavior interfaces are often empty, with the interface just being used as the vehicle for the generation extension implementations into the WCF description.
The operation contract generator extension is similar, with an IOperationBehavior instead of an IContractBehavior being the other interface implemented by the extension class.
This has popped up quite a few times in the forums, asked in different ways. Someone defines some classes in the server which are useful for the implementation, but are never referenced by the server implementation, and when they create proxies for the service, those types don’t show up. This is the design of WCF (well, if it isn’t used, it won’t be generated), but since I’ve seen it often, I decided to see if it can be accomplished via the extensibility points. And, as usual (otherwise I wouldn’t be writing about it here), there’s a way to do it in WCF, even if it’s not the easiest one.
Here’s the service I’ll use for this scenario – a calculator service for complex numbers. In this case, the complex representation is given by its “traditional” (Cartesian) coordinates (real + imaginary), but somehow we want the client to know of an alternative representation, the vectorial one (with the modulus and phase or angle defining the complex number). To help me test this sample I also added two extra types not at all relative to the scenario, but I wanted to try types in different namespaces as well.
If we host this service and create a proxy for it, only the ComplexNumber type will be generated. If we use the ServiceKnownType attribute to declare the other three data contract types to be known to the service, those types will actually be part of the schemas in the service metadata, but the WCF tools won’t emit them, because they aren’t used anywhere in the service contract.
In this sample, I wanted to add an annotation to those “unreferenced” types to indicate that they should be generated on the client, regardless of whether WCF wanted them to be. So I defined another attribute (UnreferencedServiceKnownType) as a WSDL Export extension (covered in last post) that would add those types to the service metadata and annotate them appropriately
And before long, the usual disclaimer: this is a sample for illustrating the topic of this post, this is not production-ready code. I tested it for a few contracts and it worked, but I cannot guarantee that it will work for all scenarios (please let me know if you find a bug or something missing). There are many things which can be improved, including not needing to add all the types (the code could infer that Address was needed based on Person) to the contract. Also, I don’t have a lot of experience with metadata, so it’s possible that I’m doing something which could be accomplished easier (possibly with some classes from the XML or Schema namespaces, or even WCF ones). And as usual, I’ve kept error checking to a minimum.
To implement the WSDL export extension, I’m using the XsdDataContractExporter class inside the ExportContract method. For all types which are passed to the attribute constructor, we search for them in the exporter schemas and add an annotation to be read on the client for each. The rest of the class can be found in the code gallery sample.
Now for the import extension. As usual, the implementation is quite trivial – simply add one of the contract generator extensions to the contract behavior, and let it do the work when the metadata is being imported.
The contract generator extension initializes itself by going through all of the schemas passed to it by the WSDL import extension, and adding to its XmlSchemaSet field the types which have the annotation indicating that they need to be generated on the client. The schemas are processed and since the default way that WCF exports metadata is via a modular WSDL (with the schemas being imported from the “main” document), the code deals with processing the schema import statements and loading them as well. For each “real” schema which it encounters, it calls the AddTypes method which will filter the schemas for only types which are marked with the appropriate annotation.
The implementation of the AddTypes method is the piece of code which I think there may be some clever way of accomplishing, but this worked well fine for me. Basically the code writes out the schema, then performs a XML search for the appropriate annotation. If it found any, it will remove all elements which are not related to the annotated types, then save the schema for future processing.
Finally, when GenerateContract is caled, we use the counterpart of the XsdDataContractExporter which we used in the WSDL export, the (aptly named) XsdDataContractImporter class to import the schemas we saved into a CodeCompileUnit object. When it’s done, we find out which types don’t appear in the generated code, and add those ourselves.
Now, as usual, a client to test the code. The code was “borrowed” from the Custom WSDL Publication sample, and it generates a proxy client which should contain the unreferenced types from the service as well.
Notice that I only created the proxy using the helper classes myself to make the sample self-contained. I also tried it using svcutil (creating a svcutil.exe.config and registering the extension) and it worked out just as well.
The last post of the series about metadata extensibility, about policy import / export extensions.
[Code in this post]
[Back to the index]