Tuesday, March 4, 2014

Creating a dynamic proxy

Using WCF I have been using dynamic proxies a lot. To create dynamic proxy I just use one type of class to help me out and here it is...

There is some extra code to dispose the proxy correctly and increase the serialization object graph, when passing large objects (but this can be removed if needed)

I have tested this with SOAP based services and REST based services and it worked without issues...

public class ServiceProxy<TService> : ClientBase where TService : class
{
    public ServiceProxy(string endpointName)
        : base(endpointName)
    {
        SetMaxItemsInObjectGraph(int.MaxValue);
    }


    /// 
    /// Get the service interface from the proxy
    /// 
    public TService Service { get { return base.Channel; } }


    /// 
    /// Dispose the proxy, if the proxy is a faulted state, then the communication
    /// is aborted, otherwise it is just closed. The default behavior of Dispose does
    /// not offer this logic.
    /// 
    public void Dispose()
    {
        if (State == CommunicationState.Faulted)
        {
            Abort();
        }
        else
        {
            try
            {
                this.Close();
            }
            catch
            {
                Abort();
            }
        }
    }

    private void SetMaxItemsInObjectGraph(int maxItemsInObjectGraph) where TService : class
    {
        ContractDescription contractDesc = this.Endpoint.Contract;
        foreach (var operation in contractDesc.Operations)
        {
            var behavior = operation.Behaviors.Find();
            if (behavior != null)
            {
                behavior.MaxItemsInObjectGraph = maxItemsInObjectGraph;
            }
        }
    }

To use the proxy, you would do this:

using (ServiceProxy<IMyRestService> proxy = new ServiceProxy("Client"))
{
   proxy.Service.Foo();
}

No comments: