Several public ways of known types of data contracts in WCF

Source: Internet
Author: User

The data transmitted in WCF does not want traditional object-oriented programming, it only passes the properties of some objects, but does not know what object it belongs to, so he does not have the concept of a subclass and a parent class, so there is no is-a relationship, so in WCF, if you want to maintain this inheritance relationship, We need to do some special processing.

The hypothesis is defined as follows,

namespaceKnowntypeexampleinterface
{
[DataContract]
PublicclassEmployee
{
[DataMember]
PublicstringName {get; set;}
[DataMember]
PublicstringAge {get; set;}
}

[DataContract]
PublicclassManager:employee
{
[DataMember]
PublicintOfficeId {get; set;}
}

PublicInterfaceIhumanresourceservice
{
List<employee> getallemployees ();
}
}

In this way, the manager's OfficeId cannot be obtained at the end of the call because there is no knowledge of the manager class in the service definition.

There are several ways to solve this problem

Defined in code

One way to solve this problem is to use KnownTypeAttribute to tell WCF that there is information about the manager:

[DataContract]
[Knowntype (typeof(Manager))]
Public class Employee
{
[DataMember]
Public string Name {get; set;}
[DataMember]
Public string Age {get; set;}
}

In this way, at the host side, all contracts and operations are affected, that is, the service contract or operation of the employee is used, and the manager's definition will eventually exist in the contract.

However, if you do not want the manager to be exposed to all services that use employee, you can use Serviceknowntypeattribute to apply the service definition or operation definition so that only the service or operation can accept the manager subclass.

 Public Interface Ihumanresourceservice
{
List<employee> getallemployees ();
[Serviceknowntype (typeof(Manager))]
void AddEmployee (employee employee);
}

Defined in configuration

One of the main drawbacks of defining in code is that the client must know these subclasses beforehand, add a subclass to modify the code once, recompile, and deploy, so WCF also allows these subclasses to be added by means of configuration files.

<system.runtime.serialization>
<dataContractSerializer>
<declaredTypes>
<add type="Employee,knowntypeexampleinterface,version=1.0.0.0,culture=neutral,publickeytoken=null">
<knowntype type="Manager,knowntypeexampleinterface,version=1.0.0.0,culture=neutral,publickeytoken=null"/>
</add>
</declaredTypes>
</dataContractSerializer>
</system.runtime.serialization>

Host-side Usage parser

Another way of clearing up is to use the data Contract parser, which automates the parsing of these subclasses without having to manually add tags or modify configuration files.

The method of implementing this data Contract parser

In WCF, there is a Datacontractresolver class in which you provide a dictionary of mappings between unique identifiers and types in this class, and when serializing this type, you need to provide a unique identifier as the key to form a key-type mapping relationship. WCF supplies these keys during deserialization. Referring to the data contract above, the corresponding parser is defined as:

     PublicAbstractclassManagerdatacontractresolver:datacontractresolver
    {
    PrivatestringNamespace
    {
    get {returntypeof(Manager). Namespace??"Global"; }
    }

    PrivatestringName
    {
    get {returntypeof(Manager). Name; }
    }


    PublicOverrideType ResolveName (stringTypeName,stringTypeNamespace, Type Declaredtype, Datacontractresolver knowntyperesolver)
    {
    if(TypeName = = This. Name && TypeNamespace = = This. Namespace)
    {
    return typeof(Manager);
    }
    Else
    {
    returnKnowntyperesolver.resolvename (TypeName, TypeNamespace, Declaredtype,NULL);
    }
    }

    PublicOverride BOOLTryresolvetype (Type type, type Declaredtype, Datacontractresolver knowntyperesolver, outXmlDictionaryString TypeName, outXmlDictionaryString TypeNamespace)
    {
    if(Type = =typeof(Manager))
    {
    Xmldictionary dic =NewXmldictionary ();
    TypeName = dic. ADD ( This. Name);
    TypeNamespace = dic. ADD ( This. Namespace);
    returntrue;
    }
    Else
    {
    returnKnowntyperesolver.tryresolvetype (Type, Declaredtype,NULL, outTypeName, outTypeNamespace);
    }
    }
    }

The custom parser definition is complete, then the parser needs to be installed on both the proxy and the host side.

In ServiceEndpoint there is a contract property of type Contractdascription, which is a collection of operation descriptions, each describing the operation description (OperationDescription) Contains a collection of behaviors of type Ioperationbehavior type, and each behavior contains a Datacontractresolver property, which defaults to null, which is where we can set our own custom parser.

StaticvoidMain (string[] args)
{
ServiceHost host =NewServiceHost (typeof(Humanresourceservice));
foreach(ServiceEndpoint EndpointinchHost. description.endpoints)
{
foreach(OperationDescription operationinchEndpoint. Contract.operations)
{
Datacontractserializeroperationbehavior behavior =
Operation. Operationbehaviors.firstordefault (
x = X.gettype () = =typeof(Datacontractserializeroperationbehavior)) asDatacontractserializeroperationbehavior;
Behavior. Datacontractresolver =NewManagerdatacontractresolver ();
}
}
Host. Open ();
Console.WriteLine ("Host running!");
Console.readkey ();
Host. Close ();
}

And on the agent side, you can use the same way to install the parser, not repeat!

Well, today will be here, tomorrow to do Zan residence permit, starting tomorrow I am also a legal resident in Tianjin. Hope to get your recommendation and praise, to meet the vanity will certainly contribute more to the IT cause OH

Several public ways of known types of data contracts in WCF

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.