Search code examples
code-generationwcf-clientproxy-classes

Add methods to generated WCF client proxy code


I'd like to add one additional method for each service operation in my WCF client proxy code (i.e. the generated class that derives from ClientBase). I have written a Visual Studio extension that has an IOperationContractGenerationExtension implementation, but this interface only seems to expose the ability to modify the service interface, not the ClientBase-derived class.

Is there any way to generate new methods in the proxy client class?


Solution

  • I got around this by generating a wrapper class for the ClientBase-derived class during the import process. I actually first tried generating an additional partial class with the same name as the client class, but that caused the rest of the code generation to stop working properly.

    So my final generated code looks something like:

    (generated by the built-in WCF proxy generator):

    public interface ServiceReference1
    {
        IAsyncResult BeginWebMethod1(AsyncCallback callback, object asyncState);
        void EndWebMethod1(IAsyncResult result);
    
        IAsyncResult BeginWebMethod2(AsyncCallback callback, object asyncState);
        void EndWebMethod2(IAsyncResult result);
    
        // ...
    }
    
    public class ServiceReference1Client
    {
        public event EventHandler<AsyncCompletedEventArgs> WebMethod1Completed;
        public event EventHandler<AsyncCompletedEventArgs> WebMethod2Completed;
    
        public void WebMethod1Async() { /* ... */ }
        public void WebMethod2Async() { /* ... */ }
    
        // ...
    }
    

    (generated by my custom IOperationContractGenerationExtension):

    public class ServiceReference1Wrapper
    {
        private ServiceReference1Client _client;
    
        public ServiceReference1Wrapper(ServiceReference1Client client)
        {
            _client = client;
        }
    
        public IObservable<AsyncCompletedEventArgs> WebMethod1()
        {
            _client.WebMethod1Async();
            // ...
        }
    
        public IObservable<AsyncCompletedEventArgs> WebMethod2()
        {
            _client.WebMethod2Async();
            // ...
        }
    
        // ...
    }
    

    Note: I'm using Silverlight, so that's why everything is async.