2010
03.10

A common task when consuming a WCF service is translating your business objects into the proxy objects used in a service operation call. As an example, say you’ve got a Person class, and you’re calling a WCF service operation called SaveEmployee(). When creating a reference to this service, the svcutil program will have created some proxy classes. To call the SaveEmployee() operation, you’ll need to translate your local Person object into the proxy object. Extension methods provide a nice clear way of doing this.

So, the local Person business class will be something like this:

public class Person
{
    public string Forename { get; set; }

    public string Surname { get; set; }

    public int Age { get; set; }
}

We want to call a WCF service called EmployeeService, which has an operation SaveEmployee(). This operation takes a person to save as a parameter. The type of this parameter is Employee, which svcutil has created for us in the service proxy. This may look something like this:

internal partial class Employee : 
    object, System.Runtime.Serialization.IExtensibleDataObject
{
    private string FirstNameField;
    private string LastNameField;
    private int AgeField;

    [System.Runtime.Serialization.DataMemeberAttribute()]
    internal string FirstName
    {
        get { return this.FirstNameField; }
        set { this.FirstNameField = value; }
    }

    [System.Runtime.Serialization.DataMemeberAttribute()]
    internal string LastName
    {
        get { return this.LastNameField; }
        set { this.LastNameField = value; }
    }

    [System.Runtime.Serialization.DataMemeberAttribute()]
    internal int Age
    {
        get { return this.AgeField; }
        set { this.AgeField = value; }
    }
}

As the service operation SaveEmployee needs an Employee and we have a Person, we need to translate from the latter to the former. An extension object can do this for us nicely:

internal static class PersonTranslator
{
    public static Employee TranslateToEmployee(this Person person)
    {
        return new Employee()
        {
            FirstName = person.Forename,
            LastName = person.Surname,
            Age = person.Age
        };
    }
}

Now the call to the service operation is nice and clear:

public SaveEmployee(Person person)
{
    var client = new EmployeeServiceClient();
    client.SaveEmployee(person.TranslateToEmployee());
    client.Close();
}

No Comment.

Add Your Comment