Home > Development > WCF DataContracts Exposing Subclasses via WSDL

WCF DataContracts Exposing Subclasses via WSDL

September 27, 2010 Leave a comment Go to comments

To expose your subclasses via WSDL through metadata they next to be marked as a DataContract and added to the parent classes KnownType attribute.

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

namespace WCFDataContracts.Server
{

    [DataContract]
    [KnownType(typeof(GoldCustomer))]
    public class Customer
    {

        [DataMember]
        public string Name { get; set; }
    }

    [DataContract]
    public class GoldCustomer : Customer
    {
    }

    [ServiceContract]
    public interface IPrintService
    {

        [OperationContract]
        void Print(Customer c);
    }

    public class PrintService : IPrintService
    {
        public void Print(Customer c)
        {
            Console.Write(c.Name);
        }
    }

    [ServiceContract]
    public interface ICustomerService
    {

        [OperationContract]
        void Print(Customer c);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    class CustomerService : ICustomerService
    {
        public void Print(Customer c)
        {
            Console.WriteLine(c.Name);
        }
    }

    class Program
    {
        static void Main()
        {
            Console.WriteLine("Starting Service Host");

            using(ServiceHost host = new ServiceHost(typeof(PrintService),new Uri("http://localhost/PrintService")))
            {
                ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                behavior.HttpGetEnabled = true;
                host.Description.Behaviors.Add(behavior);

                host.AddServiceEndpoint(typeof(IPrintService), new WSHttpBinding(), "");

                host.Open();

                Console.WriteLine("Press any key to exit..");
                Console.ReadKey();

            }

        }
    }
}

Hope this helps.
Blair…

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: