A preliminary study of WCF -18:WCF data contract Knowntype

Source: Internet
Author: User

KnownTypeAttribute class overview

    • When the data reaches the receive endpoint, the WCF runtime attempts to deserialize the data into an instance of the common language runtime (CLR) type. The data contract that the message content follows is determined by first checking that the incoming message selects the type instantiated for deserialization. The deserialization engine then attempts to find the CLR type that implements the data contract that is compatible with the message content. The set of candidate types that the deserialization engine allows in this procedure is called the "known type" set of the Deserializer.
    • One way to let the deserialization engine know about a type is to use KnownTypeAttribute. You cannot apply an attribute to a single data member, only it can be applied to the entire data contract type. Apply an attribute to an "external type" that might be a class or struct. In its most basic usage, applying a property specifies the type as a "known type." This causes the known type to be part of the set of known types whenever an object of the outer type is deserialized or any object referenced through its members. You can apply multiple KnownTypeAttribute properties to the same type.

The following situations require the use of KnownTypeAttribute Modifying Data Contracts

    • The data contract that was sent originates from the expected data contract. In this case, the data being transmitted does not have the same data contract as the receiving endpoint expects.
    • The declared type of information to be transmitted is an interface, not a class, struct, or enumeration. Therefore, it is not possible to know in advance which type of implementation interface is actually sent, and the receiving endpoint cannot predetermine the data contract for the transferred data.
    • The declared type of the information to be transmitted is Object. Because each type inherits from Object and cannot know in advance which type is actually sent, the receiving endpoint cannot predetermine the data contract for the transferred data. This is a special case of the first item: Each data contract originates from the default null data contract that is generated for Object.
    • Some types, including. NET Framework types, have members in one of the three categories above. For example, Hashtable uses object to store the actual object in a hash table. When these types are serialized, the recipient cannot predetermine the data contracts for those members.

Data Contract using Knowntype Example

    • The solution is as follows:

  

    • Engineering Structure Description:
    1. Service: Class Library program, WCF server-side program. Define the data contract class person in the service contract interface IUserInfo.cs, and then define a data contract class user. User derives to person, inherits the constructor of the base class person, and defines the new attribute member SayHello. Defines the operation contract GetInfo and GetInfoEx, both of which return types are person. Implementing the data contract in UserInfo.cs, in GetInfo, we return the person object type, and in GetInfoEx we return the derived class user type. Since we need to pass the derived class User type in GetInfoEx, we want to add the Knowntype (typeof (User) attribute tag to the base class data contract person, so that the user can deserialize the client for use by the client.

The IUserInfo.cs code is as follows:

Using System.ServiceModel;
Using System.Runtime.Serialization;
Using System;

Namespace Service
{
[ServiceContract]
public interface Iuserinfo
{
[OperationContract]
Person GetInfo (int id,string name);

[OperationContract]
Person GetInfoEx (int ID, string name);
}

[DataContract]
[Knowntype (typeof (User))]
public class Person
{
[DataMember]
public int ID {get; set;}

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

public person (int ID, string name)
{
This.id = ID;
This. name = name;
}
}

[DataContract]
public class User:person
{
public User (int ID, string name): Base (id,name) {}

[DataMember]
public string SayHello
{
get {return "Hello:" + Name;}
Set {throw new NotImplementedException ();}
}
}

}

The UserInfo.cs code is as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace Service
{
public class Userinfo:iuserinfo
{
Public person GetInfo (int ID, string name)
{
return new person (ID, name);
}

Public person GetInfoEx (int ID, string name)
{
return new User (ID, name);
}
}
}

2. Host: Console application, service hosting program. To add a reference to the assembly service, complete the following code, the Homestay service. The Program.cs code is as follows:

  
usingSystem;usingSystem.ServiceModel;usingService;namespacehost{classProgram {Static voidMain (string[] args) {            using(ServiceHost host =NewServiceHost (typeof(UserInfo))) {host.} Opened+=Delegate{Console.WriteLine ("Service has been started, press any key to terminate! ");                }; Host.                Open ();            Console.read (); }        }    }}
View Code

The app. Config code is as follows:

  
<?xml version="1.0"?><configuration> <system.serviceModel> <services> <service name="Service.userinfo"behaviorconfiguration="Mexbehavior"> "http://localhost:1234/UserInfo/"/> </baseAddresses> ""binding="Wshttpbinding"contract="Service.iuserinfo"/> <endpoint address="Mex"binding="mexhttpbinding"contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="Mexbehavior"> <servicemetadata httpgetenabled="true"/> <servicedebug includeexceptiondetailinfaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.servi Cemodel></configuration>
View Code

We generate client proxy classes and client configuration files through the SvcUtil.exe tool

SvcUtil.exe is a command-line tool that is located under Path C:\Program Files (x86) \microsoft Sdks\windows\v7.0a\bin, and we can run the tool from the command line to generate the client proxy class

    • Enter CMD in the run Open command line, enter CD C:\Program Files (x86) \microsoft Sdks\windows\v7.0a\bin
    • Input Svcutil.exe/out:f:\userinfoclient.cs/config:f:\app.config Http://localhost:1234/UserInfo

3. Client: A console application that invokes the program. Copy the generated UserInfoClient.cs and app. Config to the client's project directory and complete the calling code. The code for Program.cs is as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using Service;

Namespace Client
{
Class Program
{
static void Main (string[] args)
{
Try
{
Userinfoclient proxy = new Userinfoclient ();
Person P1 = proxy. GetInfo (1, "JACK");
Person P2 = proxy. GetInfoEx (2, "TOM");
Console.WriteLine ("{0,-10}{1,-20}", "ID", "Message");

Console.WriteLine ("{0,-10}{1,-20}", P1.id, P1. Name);
if (P2 is User)
{
Console.WriteLine ("{0,-10}{1,-20}", ((user) P2). ID ((user) P2). SayHello);
}
}
catch (Exception ex)
{
Console.WriteLine (ex. Message);
}

Console.read ();
}
}
}

4. The program operation effect is as follows:

  

Summary:

    • As you can see from the example above, if we need to use a data contract class that derives a subclass, and we use the subclass data contract type and the base class data contract type in the operation contract, we must add the necessary datacontract and datamember adornments for the subclass and base class members, You also need to add Knowntype to the base class data contract to tell the client that a member of the subclass needs to be deserialized.

A preliminary study of WCF -18:WCF data contract Knowntype

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.