Monday, November 26, 2012

WCF - design a reliable, extendible and consistent data exchange between consumer and provider of services

Let me share with the community with what I've learnt and successfully implemented a generalised data response (data packet) exchanged between the consumer and the provider, in context to WCF services .. 

The idea behind this concept is pretty simple! Instead of expecting a specific data type returned from the server call on its own, package that as part of a container that can facilitate not only the actual data expected by the consumer for a call to any service from the provider but additionally figure out if there were any validation/error that may have happened during that service call - all in one go! 

The following is a simple implementation within the context of using ASP.Net MVC on the front-end and Entity Framework as a ORM tool (data layer) ..

Step 1: PayLoad.cs (where the generic payload implementation lives)

    [DataContract(Name = "PayLoadListUsing={0}")]
    public class PayLoadList<TEntity>
    where TEntity : class, new()
        private TEntity _entity;

        public PayLoadList()
            _entity = new TEntity();

        public IEnumerable<TEntity> Data {get; set; }

        //design a Validation Class and make that a data member of Payload

        //design an Error Class and make that a data member of Payload

        //add anything that is required to be part of the Payload ...

Step 2: Declare an operation contract that leverages the generic payload

        PayLoadList<Student> GetStudentList();

Step 3: Under the service implementation, assign the list of data (in this case, list of Students to the *Data* member of Payload

        public PayLoadList<Student> GetStudentList()
            var ret = new PayLoadList<Student>();

            var students = DataManager.GetStudents();

            ret.Data = students;

            //ret.Error = _errorList 
            //ret.Validation = _validationList

            return ret;

Step 4: Controller/UI

Leverage GetStudentList().Data to pass as a *model* for Controller.View

No comments:

Post a Comment