Search code examples
wcfoopdatacontractservicecontract

WCF - how can I define services in a more object-oriented way?


What is the best way to access a remote object model over WCF?

I have one system layer (A) with an object-oriented model and want to access this model from another layer (B)

The required objects should be loaded by B on-demand. As an example, suppose I have classes C1 and C2 with C1 holding a List of C2. This list should be loaded only when it is accessed.

Since data contracts cannot hold operation contracts, I would implement this with one service contract with two methods "getC1" and "getListC2(C1)"

But, what I actually want is to access an object-oriented model, e.g. call a function on C1: C1.getListC2

How can I work with WCF in a more object-oriented way?


Solution

  • One way to approach this is to wrap the proxy objects with your own lazy loading (and other) business logic. In other words, let's say you have a WCF proxy called Order and a service method GetOrderLineItems().

    public class Order
    {
        private Proxies.Order _order;
        private List<OrderLineItem> _lineItems;
    
        public string Name 
        {
            get { return _order.Name; }
        }
    
        public List<OrderLineItem> LineItems
        { 
            if (_lineItems == null)
            {
                 _lineItems = //Make the service call to get these objects
            }
        }
    }
    

    Another way to synthesize this is to add extension methods to your proxy objects:

    public static List<Proxies.OrderLineItem> GetLineItems(this Proxies.Order order)
    {
         //Make the service call to get the line items
    }
    

    Which would allow you to do:

    var lineItems = order.GetLineItems();