开发者

Covariance implementaion in WCF rest service

Can covariance concept be implemented in WCF rest service,

i.e, i have class A and B inherits from It.

WCF Operation contract has input parameter A. I Should be able to pass B also to this peration.

I have a JSON client which accesses my EXF rest开发者_JS百科 service.

Is it possible i imeplement covariance concept . How should i do this in server and client. Pls Help.


Of course! The only thing that's required for this to work is for you to add class B to the list of types that the service should know about using the ServiceKnownType attribute.

Here's a quick example I put together to demonstrate this, imagine this is your service contract:

using System.Runtime.Serialization;
using System.ServiceModel;

namespace WcfCovariance
{
    [ServiceKnownType(typeof(Employee))]
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        Person GetPerson();

        [OperationContract]
        Person PutPerson(Person person);
    }

    [DataContract]
    public class Person
    {
        [DataMember]
        public string Name { get; set; }
    }

    [DataContract]
    public class Employee : Person
    {
        [DataMember]
        public double Salary { get; set; }
    }
}

And the implementation:

namespace WcfCovariance
{
    public class Service1 : IService1
    {
        static Person Singleton = new Person { Name = "Me" };

        public Person GetPerson()
        {
            return Singleton;
        }

        public Person PutPerson(Person person)
        {
            Singleton = person;

            return Singleton;
        }
    }
}

Because you've told WCF about the type Employee using the ServiceKnownType attribute, when it's encountered (both in the input parameters and in response) it'll be able to serialize/deserialize it, be it using JSON or not.

Here's a simple client:

using System;
using WcfCovarianceTestClient.CovarianceService;

namespace WcfCovarianceTestClient
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new Service1Client("WSHttpBinding_IService1");

            // test get person
            var person = client.GetPerson();

            var employee = new Employee { Name = "You", Salary = 40 };
            client.PutPerson(employee);

            var person2 = client.GetPerson();

            // Employee, if you add breakpoint here, you'd be able to see that it has all the correct information
            Console.WriteLine(person2.GetType()); 

            Console.ReadKey();
        }
    }
}

It's very common to pass subtypes to and from a WCF service, the only thing you won't be able to do though is to specify an interface as the response in your contract.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜