博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WCF数据契约代理和已知类型的使用
阅读量:5933 次
发布时间:2019-06-19

本文共 6599 字,大约阅读时间需要 21 分钟。

using Bll;using System;using System.CodeDom;using System.Collections.Generic;using System.Collections.ObjectModel;using System.Diagnostics;using System.Linq;using System.Reflection;using System.Runtime.Serialization;using System.ServiceModel;using System.ServiceModel.Description;using System.Text;using System.Threading.Tasks;using System.Xml;namespace Distributed.Model{    #region 1.1 已知类型KnownType [KnownType(typeof(T))]    [DataContract]    //[KnownType(typeof(Bar))]    //[KnownType(typeof(Baz))]    public class Foo    {    }    [DataContract]    public class Bar : Foo    {    }    [DataContract]    public class Baz : Bar    {    }    #endregion    #region 1.2 KnownType 指定方法名 GetKnownTypes    //[DataContract]    //[KnownType("GetKnownTypes")]    //public class Foo    //{    //    public static IEnumerable
GetKnownTypes() // { // yield return typeof(Bar); // yield return typeof(Baz); // } //} #endregion #region 2. ServiceKnownType指定解析类KnownTypeResolver和方法GetKnownTypes [ServiceContract(Namespace = "www.holworth.com")] [ServiceKnownType("GetKnownTypes", typeof(KnownTypeResolver))] public interface IContract { [OperationContract] void DoSomething(Foo foo); } public static class KnownTypeResolver { public static IEnumerable
GetKnownTypes(ICustomAttributeProvider provider) { yield return typeof(Bar); yield return typeof(Baz); } } #endregion [DataContract] public class Contract { [DataMember] public string FullName { get; set; } [DataMember] public string Sex { get; set; } } [DataContract] public class Custmoer { [DataMember] public string FirstName { get; set; } [DataMember] public string LastName { get; set; } [DataMember] public string Gender { get; set; } } ///
/// 目标进入契约对象,出来也是契约对象 /// public class ContractSurrogate : IDataContractSurrogate { public Type GetDataContractType(Type type) { if (type == typeof(Contract)) { return typeof(Custmoer); } return type; } ///
/// obj /// ///
obj是序列化之后的对象,我们的目标是反序列化得到原始类型Contract ///
///
public object GetDeserializedObject(object obj, Type targetType) { Custmoer customer = obj as Custmoer; if (customer == null) { return obj; } return new Contract() { FullName = customer.FirstName + " " + customer.LastName, Sex = customer.Gender }; } ///
/// /// ///
原始契约对象类型Contract ///
///
public object GetObjectToSerialize(object obj, Type targetType) { Contract contract = obj as Contract; if (contract == null) { return obj; } return new Custmoer() { FirstName = contract.FullName.Split(" ".ToCharArray())[0], LastName = contract.FullName.Split(" ".ToCharArray())[1], Gender = contract.Sex }; } public void GetKnownCustomDataTypes(Collection
customDataTypes) { } public object GetCustomDataToExport(Type clrType, Type dataContractType) { return null; } public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType) { return null; } public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData) { return null; } public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit) { return typeDeclaration; } } public class Program { public static void Serializer
(T instance, string fileName, IDataContractSurrogate dataContractSurrogate) { DataContractSerializer serializer = new DataContractSerializer(typeof(T), null, int.MaxValue, false, false, dataContractSurrogate); using (XmlWriter writer = new XmlTextWriter(fileName, Encoding.UTF8)) { serializer.WriteObject(writer, instance); Process.Start(fileName); } } public static T Deserializer
(string fileName, IDataContractSurrogate dataContractSurrogate) { DataContractSerializer serializer = new DataContractSerializer(typeof(T), null, int.MaxValue, false, false, dataContractSurrogate); using (XmlReader reader = new XmlTextReader(fileName)) { return (T)serializer.ReadObject(reader); } } public static void Host() { using (ServiceHost serviceHost = new ServiceHost(typeof(BasCurrencyService))) foreach (ServiceEndpoint ep in serviceHost.Description.Endpoints) { foreach (OperationDescription op in ep.Contract.Operations) { DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find
() as DataContractSerializerOperationBehavior; if (op.Behaviors.Find
() != null) { dataContractBehavior.DataContractSurrogate = new ContractSurrogate(); } op.Behaviors.Add(op.Behaviors.Find
()); dataContractBehavior = new DataContractSerializerOperationBehavior(op); dataContractBehavior.DataContractSurrogate =new ContractSurrogate(); op.Behaviors.Add(dataContractBehavior); } } } public static void main(string[] args) { //1.1 实验输出 string fileName = "contract.xml"; Contract contract = new Contract() { FullName = "ke xiangbin", Sex = "Male" }; IDataContractSurrogate dataContractSurrogate = new ContractSurrogate(); Serializer
(contract, fileName, dataContractSurrogate); Console.WriteLine("序列化前"); Console.WriteLine("\t{0,-9}:{1}", "FullName", contract.FullName); Console.WriteLine("\t{0,-9}:{1}", "Sex", contract.Sex); contract = Deserializer
(fileName, dataContractSurrogate); Console.WriteLine("反序列化后"); Console.WriteLine("\t{0,-9}:{1}", "FullName", contract.FullName); Console.WriteLine("\t{0,-9}:{1}", "Sex", contract.Sex); //1.2 服务寄宿应用数据契约代理 Host(); Console.ReadKey(); } }}

 

转载于:https://www.cnblogs.com/kexb/p/8191909.html

你可能感兴趣的文章
linux 3.10的list_del
查看>>
20170521第三讲
查看>>
Opencv学习之路—Opencv下基于HOG特征的KNN算法分类训练
查看>>
12.7日个人工作总结
查看>>
关键路径
查看>>
错误处理和调试 - C++快速入门30
查看>>
正则表达式测试工具之Regex Match Tracer
查看>>
vba基础知识
查看>>
建一个网站python
查看>>
Redis缓存数据之简单逻辑
查看>>
面向对象程序设计第六次作业(初步)
查看>>
数学对于程序员来说有多重要?
查看>>
大话前端组件化
查看>>
集线器与交换机的区别
查看>>
WPF 自定义ItemsControl/ListBox/ListView控件样式
查看>>
父亲节点的实现
查看>>
2015年6月10日晨_学习并复习
查看>>
「学习笔记」左偏树
查看>>
今天是高考最后一天了!做好迎接崭新未来的准备了吗?
查看>>
C++ this指针的详解
查看>>