我的WCF之旅(7):面向服务架构(SOA)和面向对象编程(OOP)的结合——如何实现Service Contract的继承

当今的IT领域,SOA已经成为了一个非常时髦的词,对SOA风靡的程度已经让很多人对SOA,对面向服务产生误解。其中很大一部分人甚至认为面向服务将是面向对象的终结,现在的面向对象将会被面向服务完全代替。在开始本Blog之前,我先来谈谈我对SOA和OO的区别,首先申明,这只是一家之言,欢迎大家批评指正,并且关于SO的谈论不是本Blog的主题,只是主题的引子,在这里只是简单讨论而已 。

OO和SO之间具有共同的部分,在运用的领域上存在交集,只有在基于他们交集层面上谈论谁是谁非才有意义,下面是我对SO和OO的区别。

OO关注的是如何通过对实体属性和行为的封装来重塑模拟软件环境的真实实体。对SO关注的则是对现实生活的某个任务、功能的实现,说得通俗点,就是如果做好一件事情。所以对象是对Data和Behavior的封装,而Service则只是体现了一个Functionality。Service是粗粒度的,这样才能导致Contract的稳定;Service一般是Stateless的,给定什么样的输入,就会有对应的确定的输出;Service是Autonomous,基本上的实现封装在Service本身之中,这样可以使它对其它的Service产生最小的依赖。所以对Service建模是一件不太容易的事情:Service不能太大,否则实现起来不容易,还会增加对外界的依赖;也不能太小,否则整合这个Service的成本会令你望而却步。

Service是可组合的(Composable),通过整合相关的单独的,完成某个单个Task或者Activity的小的Service,可以很容易产生一个大的Service,这个Service可以完成一个Functionality的整个流程。比如我们现在把一个Task描述成一个Work flow,如果采用SO的原理来建模,我们可以把组成这个Workflow的单个Activity设计成一个service, 然后根据具体Workflow的特点(比如可能是一个简单的Sequential workflow,也可能是一个基于State machine的workflow)加上相关的条件很容易的把这些Service整合起来,实际上通过整合集成,我们生成一个新的Service。对OO,由于他面对的是一个的Object,具体在分布式中是一个个的Distributed object,要建立一个Composable object则很难(实际上这样也没有什么意义)。

在OO的概念中,一个Object的属性往往就是另一个Object,一个Function的实现往往要调用另一个Object的方法,而且这种层次结构可以无限延伸。这样就会导致真个Object体系变得异常脆弱,经常造成牵一发动全身的状况。用一个很时髦的词语来表达的,就是紧耦合(Tightly couple),Object之间的强依赖关系促成了这种紧耦合的、脆弱的体系结构。而OS则不一样,由于 构成Service体系的单个Service是自治的,Service之间的调用(调用的这个词语容易让人联想到RPC,如果找一个比较贴切的词语来代替,我觉得consume比较合适)是基于Contract的,Service之间Communication是通过Message的(Message不仅仅是Data的封装,还是对整个调用的描述,同时基于XML的Message描述和Message的传递都是符合一个开放的标准的),所有这些成就了SO的松耦合(Loosely couple)。

说了这么多,可能大家都觉得我都是在赞扬SO,都贬低OO。其实不然,上面所说的3个方面都是在讲应用的构建,而不是具体的编程模式。我想表达的是,曾经盛行的基于OO的理论,在企业应用构架方面,已经不能满足我们的需要了,我们迫切希望一种全新的理论来指导我们进行企业应用的构架和集成,而这个理论非SO不可。

而在编程模型层面,OO仍然是不可替代的编程模式。所以OO应用于Programming,而SO则更多地运用在Architecture。既然是这样,我们必须有一种调和剂来调和这两个运用不同原理的两个层面的差异,实现他们之间的无缝的结合。比如如何来对继承,多态,重载等基于OO行为的支持。在这方面,WCF为我们提供了很好的解决方案。所以我说WCF不但是为基于SOA的应用架构提供了技术支持,还通过相关的机制完成我们提出的这个“调和剂”的使命。

在上一篇文章[原创]我的WCF之旅(5):面向服务架构(SOA)对面向对象编程(OOP)的支持——如何实现Service Contract的重载(Overloading)中,我们谈到了WCF如何实现了对Overloading的支持,在这里我们通过一个Sample来讨论WCF对继承的支持。这个Sample中,我们通过一个WCF Service实现了提供天气信息的功能,或者说,我们实现了一个用作天气预报的WCF Service。

1.    我们照例来看看真个Solution 的结构:

整个Solution由以下4个project构成:

  • Artech.InheritanceHierarchy.BusinessEntity:这个Project通过定义的Class封装了在Client和Service端传递的数据,在本例中,我们定义了两个Class:BasicWhetherInfo和WindInfo,他们分别表示Client通过Service获得的基本天气情况和刮风的情况。
  •  Artech.InheritanceHierarchy.Service:这个Project是我们的Service,包括Service Contract和Service 本身。我们定义两个用作天气预报的Service:SimpleWhetherForecast和FullWhetherForecast,前面一个只用返回简单的天气状况的数据(Conditions和Temperature),FullWhetherForecast在SimpleWhetherForecast基础上增加了提供风向和风速的数据。
  • http://localhost/Artech.InheritanceHierarchy: 一个WCF Service Website,以IIS的方式对Service进行Host。
  • Artech.InheritanceHierarchy.Client: Client端。

2.    定义Artech.InheritanceHierarchy.BusinessEntity

BasicWhetherInfo.cs:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace Artech.InheritanceHierarchy.BusinessEntity
{
    [DataContract]    
    [KnownType(typeof(WhetherConditions))]
    public class BasicWhetherInfo
    {
        private WhetherConditions _condition;      
        private double _temperature;

        public BasicWhetherInfo(WhetherConditions condition, double temperature)
        {
            this._condition = condition;
            this._temperature = temperature;
        }

        [DataMember]
        public WhetherConditions Condition
        {
            get { return _condition; }
            set { _condition = value; }
        }

        [DataMember]
        public double Temperature
        {
            get { return _temperature; }
            set { _temperature = value; }
        }

        public override string ToString()
        {
            return string.Format("Conditions: {0}; Temperature: {1}", this._condition, this._temperature);
        }
    }

    public enum WhetherConditions
    { 
        Clear,
        Cloudy,
        Overcost,
        Rainy
    }
}

BasicWhetherInfo包含连个字段/属性:Condition和Temperature。属于Condition不属于基元(Primitive type)所以我们需要添加    [KnownType(typeof(WhetherConditions))]Attribute(由于跨AppDomain的数据传递要求传递的数据先辈Serialization。对于.NET中定义的Primitive type,比如string,int以及其他一些常用的类型,比如datetime,WCF具有一套默认的序列化机制,但是对于另外一些类型,Serializor在执行Serialization的时候 需要获得相关类型的Metadata的信息,WCF通过KnownType attribute向Serializor提供Metadata的信息。)。WindInfo中的Direction属性也是一样的原理。 

WindInfo.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace Artech.InheritanceHierarchy.BusinessEntity
{
    [DataContract]
    [KnownType(typeof(WindDirection))]
    public class WindInfo
    {
        private WindDirection _direction;       
        private string _speed;

        public WindInfo(WindDirection direction, string speed)
        {
            this._direction = direction;
            this._speed = speed;
        }

        [DataMember]
        public WindDirection Direction
        {
            get { return _direction; }
            set { _direction = value; }
        }

        [DataMember]
        public string Speed
        {
            get { return _speed; }
            set { _speed = value; }
        }

        public override string ToString()
        {
            return string.Format("Direction: {0}; Speed: {1}", this._direction, this._speed);
        }
    }

    public enum WindDirection
    { 
        East,
        South,
        West,
        North,
        Northeast,
        SouthEast,
        Northwest,
        Southwest
    }
}

3.    定义Service:Artech.InheritanceHierarchy.Service

我们首先来定义Service Contract

ISimpleWhetherForecast.cs:

using System;
using System.Collections.Generic;
using System.Text;

using Artech.InheritanceHierarchy.BusinessEntity;
using System.ServiceModel;

namespace Artech.InheritanceHierarchy.Service
{
    [ServiceContract]
    public interface ISimpleWhetherForecast
    {
        [OperationContract]
        BasicWhetherInfo GetBasicWhetherInfo(string postalcode);
    }
}

IFullWhetherForecast.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using Artech.InheritanceHierarchy.BusinessEntity;

namespace Artech.InheritanceHierarchy. Service
{
    [ServiceContract]
    public interface IFullWhetherForecast:ISimpleWhetherForecast
    {
        [OperationContract]
        WindInfo GetWindInfo(string postalcode);
    }
}

我们定义了连个Interface作为Service Contract。其中IFullWhetherForecast继承ISimpleWhetherForecast。这里需要注意的是虽然IFullWhetherForecast继承ISimpleWhetherForecast,但是运用在ISimpleWhetherForecast中的ServiceContract Attribute却不能被IFullWhetherForecast使用,这是因为在定义System.ServiceModel. ServiceContractAttribute, 把运用在它之上的AttributeUsage的Inherited设为false, 导致它不能运用到派生的Class上面:

using System;
using System.Net.Security;

namespace System.ServiceModel
{
    [AttributeUsage(1028, Inherited = false, AllowMultiple = false)]
    public sealed class ServiceContractAttribute : Attribute
    {
        public ServiceContractAttribute();

        public Type CallbackContract { get; set; }
        public string ConfigurationName { get; set; }
        public bool HasProtectionLevel { get; }
        public string Name { get; set; }
        public string Namespace { get; set; }
        public ProtectionLevel ProtectionLevel { get; set; }
        public SessionMode SessionMode { get; set; }
    }
}

我们接着为这两个Service Contract定义对应的Service。

SimpleWhetherForecastService:

using System;
using System.Collections.Generic;
using System.Text;
using Artech.InheritanceHierarchy.BusinessEntity;

namespace Artech.InheritanceHierarchy.Service
{
    public class SimpleWhetherForecastService:ISimpleWhetherForecast
    {
        ISimpleWhetherForecast Members#region ISimpleWhetherForecast Members

        public BasicWhetherInfo GetBasicWhetherInfo(string postalcode)
        {
            BasicWhetherInfo info = new BasicWhetherInfo(WhetherConditions.Overcost, 23);
            return info;
        }

        #endregion
    }
}

为了代码的重用,我们让FullWhetherForecastService继承自SimpleWhetherForecastService,这样我们就不必重新定义GetBasicWhetherInfo方法了。

FullWhetherForecastService.cs:

using System;
using System.Collections.Generic;
using System.Text;
using Artech.InheritanceHierarchy.BusinessEntity;

namespace Artech.InheritanceHierarchy.Service
{
   public class FullWhetherForecastService:SimpleWhetherForecastService,IFullWhetherForecast
    {
        IFullWhetherForecast Members#region IFullWhetherForecast Members

        public WindInfo GetWindInfo(string postalcode)
        {
            WindInfo info = new WindInfo(WindDirection.Northwest, "12km/h");
            return info;
        }
        #endregion      
    }
}

4.    Host Service:http://localhost/Artech.InheritanceHierarchy

现在我们完成了Service的定义,现在我们来Host我们定义的Service,这次我们通过IIS的方式来host service。我们首先在该Website中引用Artech.InheritanceHierarchy.Service Project。然后为FullWhetherForecastService定义相应的.SVC文件(由于Service Contract的继承关系构成了一种Service Contract的层次结构,从而导致所有定义的Operation都出现在最底层的Contract中,由于SimpleWhetherForecastService的Operation没有被FullWhetherForecastServiceOverride,所以现在我们只需要Host FullWhetherForecastService就可以了)。

<%@ ServiceHost Service="Artech.InheritanceHierarchy.Service.FullWhetherForecastService,Artech.InheritanceHierarchy.Service" %>

接着我们在Web.config中为Service注册Endpoint。

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
    <system.serviceModel>
        <services>            
            <service name="Artech.InheritanceHierarchy.Service.FullWhetherForecastService" behaviorConfiguration="returnFaults">
                <endpoint contract="Artech.InheritanceHierarchy.Service.IFullWhetherForecast" binding="wsHttpBinding"/>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="returnFaults">
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                    <serviceMetadata httpGetEnabled="true" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>
    <system.web>
        <compilation debug="true">
            <assemblies>
                <add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
                <add assembly="Microsoft.Transactions.Bridge, Version=3.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
                <add assembly="SMDiagnostics, Version=3.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.IdentityModel.Selectors, Version=3.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
                <add assembly="System.Web.RegularExpressions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
                <add assembly="System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Messaging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
                <add assembly="System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/></assemblies></compilation>
    </system.web>
</configuration>

5.    定义Client:Artech.InheritanceHierarchy.Client

到现在为止,我们完成了Service的定义和Host的工作,换句话说现在我们定义的Whether

 Forecast service已经可以访问,并暴露在这样的一个Address上:http://localhost/Artech.InheritanceHierarchy/FullWhetherForecastService.svc。现在我们来编写我们Client来访问这个Service。值得一说的是,现在这个Sample中,Client是一个独立的Application,我们既没有让他引用我们定义的Artech.InheritanceHierarchy.BusinessEntity(在WCF中,这个相当于Data Contract),也没有让它和Service共享同一个Service Contract。这很类似于在纯Web环境下调用Service。

我们通过添加Service reference的方式生成我们Client端的code, WCF中的添加Service reference同Web Service中的添加Web reference相识。通过添加Service reference,WCF会为我们生成基于Client的service contract,data contract,proxy,configuraiton,甚至为我们添加System.ServiceNModel dll的引用。下面就是我们生成的Code:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.312
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Artech.InheritanceHierarchy.Client.WhetherForecastService
{
    using System.Runtime.Serialization;
    using System;
    
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://schemas.datacontract.org/2004/07/Artech.InheritanceHierarchy.BusinessEntit" +
        "y")]
    [System.SerializableAttribute()]
    public partial class BasicWhetherInfo : object, System.Runtime.Serialization.IExtensibleDataObject
    {
        
        [System.NonSerializedAttribute()]
        private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private Artech.InheritanceHierarchy.Client.WhetherForecastService.WhetherConditions ConditionField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private double TemperatureField;
        
        public System.Runtime.Serialization.ExtensionDataObject ExtensionData
        {
            get
            {
                return this.extensionDataField;
            }
            set
            {
                this.extensionDataField = value;
            }
        }
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public Artech.InheritanceHierarchy.Client.WhetherForecastService.WhetherConditions Condition
        {
            get
            {
                return this.ConditionField;
            }
            set
            {
                this.ConditionField = value;
            }
        }
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public double Temperature
        {
            get
            {
                return this.TemperatureField;
            }
            set
            {
                this.TemperatureField = value;
            }
        }
    }
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://schemas.datacontract.org/2004/07/Artech.InheritanceHierarchy.BusinessEntit" +
        "y")]
    public enum WhetherConditions : int
    {
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Clear = 0,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Cloudy = 1,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Overcost = 2,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Rainy = 3,
    }
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://schemas.datacontract.org/2004/07/Artech.InheritanceHierarchy.BusinessEntit" +
        "y")]
    [System.SerializableAttribute()]
    public partial class WindInfo : object, System.Runtime.Serialization.IExtensibleDataObject
    {
        
        [System.NonSerializedAttribute()]
        private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private Artech.InheritanceHierarchy.Client.WhetherForecastService.WindDirection DirectionField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string SpeedField;
        
        public System.Runtime.Serialization.ExtensionDataObject ExtensionData
        {
            get
            {
                return this.extensionDataField;
            }
            set
            {
                this.extensionDataField = value;
            }
        }
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public Artech.InheritanceHierarchy.Client.WhetherForecastService.WindDirection Direction
        {
            get
            {
                return this.DirectionField;
            }
            set
            {
                this.DirectionField = value;
            }
        }
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public string Speed
        {
            get
            {
                return this.SpeedField;
            }
            set
            {
                this.SpeedField = value;
            }
        }
    }
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://schemas.datacontract.org/2004/07/Artech.InheritanceHierarchy.BusinessEntit" +
        "y")]
    public enum WindDirection : int
    {
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        East = 0,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        South = 1,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        West = 2,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        North = 3,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Northeast = 4,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        SouthEast = 5,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Northwest = 6,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Southwest = 7,
    }
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName="Artech.InheritanceHierarchy.Client.WhetherForecastService.IFullWhetherForecast")]
    public interface IFullWhetherForecast
    {
        
        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ISimpleWhetherForecast/GetBasicWhetherInfo", ReplyAction="http://tempuri.org/ISimpleWhetherForecast/GetBasicWhetherInfoResponse")]
        Artech.InheritanceHierarchy.Client.WhetherForecastService.BasicWhetherInfo GetBasicWhetherInfo(string postalcode);
        
        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IFullWhetherForecast/GetWindInfo", ReplyAction="http://tempuri.org/IFullWhetherForecast/GetWindInfoResponse")]
        Artech.InheritanceHierarchy.Client.WhetherForecastService.WindInfo GetWindInfo(string postalcode);
    }
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    public interface IFullWhetherForecastChannel : Artech.InheritanceHierarchy.Client.WhetherForecastService.IFullWhetherForecast, System.ServiceModel.IClientChannel
    {
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    public partial class FullWhetherForecastClient : System.ServiceModel.ClientBase<Artech.InheritanceHierarchy.Client.WhetherForecastService.IFullWhetherForecast>, Artech.InheritanceHierarchy.Client.WhetherForecastService.IFullWhetherForecast
    {
        
        public FullWhetherForecastClient()
        {
        }
        
        public FullWhetherForecastClient(string endpointConfigurationName) : 
                base(endpointConfigurationName)
        {
        }
        
        public FullWhetherForecastClient(string endpointConfigurationName, string remoteAddress) : 
                base(endpointConfigurationName, remoteAddress)
        {
        }
        
        public FullWhetherForecastClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
                base(endpointConfigurationName, remoteAddress)
        {
        }
        
        public FullWhetherForecastClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
                base(binding, remoteAddress)
        {
        }
        
        public Artech.InheritanceHierarchy.Client.WhetherForecastService.BasicWhetherInfo GetBasicWhetherInfo(string postalcode)
        {
            return base.Channel.GetBasicWhetherInfo(postalcode);
        }
        
        public Artech.InheritanceHierarchy.Client.WhetherForecastService.WindInfo GetWindInfo(string postalcode)
        {
            return base.Channel.GetWindInfo(postalcode);
        }
    }
}

Code比较长,我们现在一部分一部分地来分析。

Part I:Data Contract

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://schemas.datacontract.org/2004/07/Artech.InheritanceHierarchy.BusinessEntit" +
        "y")]
    [System.SerializableAttribute()]
    public partial class BasicWhetherInfo : object, System.Runtime.Serialization.IExtensibleDataObject
    {
        
        [System.NonSerializedAttribute()]
        private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private Artech.InheritanceHierarchy.Client.WhetherForecastService.WhetherConditions ConditionField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private double TemperatureField;
        
        public System.Runtime.Serialization.ExtensionDataObject ExtensionData
        {
            get
            {
                return this.extensionDataField;
            }
            set
            {
                this.extensionDataField = value;
            }
        }
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public Artech.InheritanceHierarchy.Client.WhetherForecastService.WhetherConditions Condition
        {
            get
            {
                return this.ConditionField;
            }
            set
            {
                this.ConditionField = value;
            }
        }
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public double Temperature
        {
            get
            {
                return this.TemperatureField;
            }
            set
            {
                this.TemperatureField = value;
            }
        }
    }
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://schemas.datacontract.org/2004/07/Artech.InheritanceHierarchy.BusinessEntit" +
        "y")]
    public enum WhetherConditions : int
    {
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Clear = 0,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Cloudy = 1,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Overcost = 2,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Rainy = 3,
    }
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://schemas.datacontract.org/2004/07/Artech.InheritanceHierarchy.BusinessEntit" +
        "y")]
    [System.SerializableAttribute()]
    public partial class WindInfo : object, System.Runtime.Serialization.IExtensibleDataObject
    {
        
        [System.NonSerializedAttribute()]
        private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private Artech.InheritanceHierarchy.Client.WhetherForecastService.WindDirection DirectionField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string SpeedField;
        
        public System.Runtime.Serialization.ExtensionDataObject ExtensionData
        {
            get
            {
                return this.extensionDataField;
            }
            set
            {
                this.extensionDataField = value;
            }
        }
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public Artech.InheritanceHierarchy.Client.WhetherForecastService.WindDirection Direction
        {
            get
            {
                return this.DirectionField;
            }
            set
            {
                this.DirectionField = value;
            }
        }
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public string Speed
        {
            get
            {
                return this.SpeedField;
            }
            set
            {
                this.SpeedField = value;
            }
        }
    }
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://schemas.datacontract.org/2004/07/Artech.InheritanceHierarchy.BusinessEntit" +
        "y")]
    public enum WindDirection : int
    {
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        East = 0,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        South = 1,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        West = 2,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        North = 3,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Northeast = 4,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        SouthEast = 5,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Northwest = 6,
        
        [System.Runtime.Serialization.EnumMemberAttribute()]
        Southwest = 7,
}

把这段代码基本上对应的我们在Artech.InheritanceHierarchy.BusinessEntity定义的Data Contract:两个Class:BasicWhetherInfo& WindInfo和连个Enum:WindDirection& WhetherConditions。不过有一点我觉得奇怪的是我们原来的BasicWhetherInfo& WindInfo的定义中,我Override了ToString方法,但是在生成的Class中,却没有相应的Code。我不清楚Microsoft对此事作怎么样的考虑,还是忽略了这一点。

Part II Service Contract

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]    [System.ServiceModel.ServiceContractAttribute(ConfigurationName="Artech.InheritanceHierarchy.Client.WhetherForecastService.IFullWhetherForecast")]
    public interface IFullWhetherForecast
    {        
        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ISimpleWhetherForecast/GetBasicWhetherInfo", ReplyAction="http://tempuri.org/ISimpleWhetherForecast/GetBasicWhetherInfoResponse")]
        Artech.InheritanceHierarchy.Client.WhetherForecastService.BasicWhetherInfo GetBasicWhetherInfo(string postalcode);
        
        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IFullWhetherForecast/GetWindInfo", ReplyAction="http://tempuri.org/IFullWhetherForecast/GetWindInfoResponse")]
        Artech.InheritanceHierarchy.Client.WhetherForecastService.WindInfo GetWindInfo(string postalcode);
    }

在Service端,我们通过运用继承定义了一套Service contract的层次结构,并为处于最底层的Contract公开了一个Endpoint。在Client端,我们通过添加Service reference的方式生成了Client的Service contract的结构。不过Client的Service contract的结构是一种扁平的结构:通过一个Contract定义所有的Operation。

Part III Proxy

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    public interface IFullWhetherForecastChannel : Artech.InheritanceHierarchy.Client.WhetherForecastService.IFullWhetherForecast, System.ServiceModel.IClientChannel
    {
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    public partial class FullWhetherForecastClient : System.ServiceModel.ClientBase<Artech.InheritanceHierarchy.Client.WhetherForecastService.IFullWhetherForecast>, Artech.InheritanceHierarchy.Client.WhetherForecastService.IFullWhetherForecast
    {
        
        public FullWhetherForecastClient()
        {
        }
        
        public FullWhetherForecastClient(string endpointConfigurationName) : 
                base(endpointConfigurationName)
        {
        }
        
        public FullWhetherForecastClient(string endpointConfigurationName, string remoteAddress) : 
                base(endpointConfigurationName, remoteAddress)
        {
        }
        
        public FullWhetherForecastClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
                base(endpointConfigurationName, remoteAddress)
        {
        }
        
        public FullWhetherForecastClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
                base(binding, remoteAddress)
        {
        }
        
        public Artech.InheritanceHierarchy.Client.WhetherForecastService.BasicWhetherInfo GetBasicWhetherInfo(string postalcode)
        {
            return base.Channel.GetBasicWhetherInfo(postalcode);
        }
        
        public Artech.InheritanceHierarchy.Client.WhetherForecastService.WindInfo GetWindInfo(string postalcode)
        {
            return base.Channel.GetWindInfo(postalcode);
        }
}

现在我们可以通过FullWhetherForecastClient这个Proxy Class来访问Service了。虽然能完成我们的所有操作,但是这样的代码总觉得很别扭。我们希望的是以Service端定义结构进行Service的调用:Client具有两个Proxy:SimpleWhetherForecastClient和FullWhetherForecastClient。FullWhetherForecastClient继承自SimpleWhetherForecastClient。我们先删除我们生成的Code,按照以下的步骤来实现这样功能。

Step 1:定义Client端的Service Contract

ISimpleWhetherForecast

using System;
using System.Collections.Generic;
using System.Text;

using Artech.InheritanceHierarchy.BusinessEntity;
using System.ServiceModel;

namespace Artech.InheritanceHierarchy.Client
{
    [ServiceContract]
    public interface ISimpleWhetherForecast
    {
        [OperationContract]
        BasicWhetherInfo GetBasicWhetherInfo(string postalcode);
    }
}

IFullWhetherForecast.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using Artech.InheritanceHierarchy.BusinessEntity;

namespace Artech.InheritanceHierarchy. Client
{
    [ServiceContract]
    public interface IFullWhetherForecast:ISimpleWhetherForecast
    {
        [OperationContract]
        WindInfo GetWindInfo(string postalcode);
    }
}

除了namespace,和Service端的contract没有什么区别。

Step2:引用Artech.InheritanceHierarchy.BusinessEntity

Step3:   配置Endpoint

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <client>            
            <endpoint address="http://localhost/Artech.InheritanceHierarchy/FullWhetherForecastService.svc"
              binding="wsHttpBinding" bindingConfiguration=""  contract="Artech.InheritanceHierarchy.Client.IFullWhetherForecast"/>
        </client>
    </system.serviceModel>
</configuration>

因为Service端的Endpoint对应的Contract是Artech.InheritanceHierarchy.Service IFullWhetherForecast,所以我们适应对应的Client端的Contract:Artech.InheritanceHierarchy.Client.IFullWhetherForecast

Step 4:建立Proxy

SimpleWhetherForecastClient.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using Artech.InheritanceHierarchy.BusinessEntity;

namespace Artech.InheritanceHierarchy.Client
{
   public class SimpleWhetherForecastClient:ClientBase<IFullWhetherForecast>,ISimpleWhetherForecast
    {
       ISimpleWhetherForecast Members#region ISimpleWhetherForecast Members

        public BasicWhetherInfo GetBasicWhetherInfo(string postalcode)
        {
            return this.Channel.GetBasicWhetherInfo(postalcode);
        }

        #endregion
    }
}

FullWhetherForecastClient.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace Artech.InheritanceHierarchy.Client
{
    public class FullWhetherForecastClient:SimpleWhetherForecastClient,IFullWhetherForecast
    {
       
        IFullWhetherForecast Members#region IFullWhetherForecast Members

        public Artech.InheritanceHierarchy.BusinessEntity.WindInfo GetWindInfo(string postalcode)
        {
            return this.Channel.GetWindInfo(postalcode);
        }

        #endregion
    }
}

现在通过SimpleWhetherForecastClient和FullWhetherForecastClient完全以OO的方式优雅地调用Whether forecast service。

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏草根专栏

使用C# (.NET Core) 实现状态设计模式 (State Pattern)

53350
来自专栏me的随笔

模板方法模式实践

在实际编程中,会经常遇到多个类中的某些方法实现逻辑类似的情况,这时我们可以将这些类中的相同部分抽象到父类中,对于有差异的地方,子类根据自身的实际需求来各自实现。

11220
来自专栏SDNLAB

ONOS集群选举分析

首先简单介绍下自己,之前是做 floodlight 控制器开发的,鉴于 ODL 和 onos 的如火如荼的发展,如果不对了解点就感觉自己 OUT 了,因此忙里偷...

37660
来自专栏GIS讲堂

一个GISER 6.7的祝福

一年一度的高考今天开始了,回想10年前,那是我第一次高考;10年后,作为一个GISER,在此给大家献上一个GISER的祝福,祝愿各位考生:考神附体,考完报考GI...

15840
来自专栏Java成神之路

Java微信公众平台开发_06_素材管理

32320
来自专栏木宛城主

深入浅出三层架构

这几天看了不少三层架构的资料,整理整理 ——故写篇博文谈谈自己的看法。 三层架构概念: 三层架构(3-tier application) 通常意义上的三层架构就...

26550
来自专栏菩提树下的杨过

silverlight向wcf传递大于8192字节(8k)的字符串

默认情况下,silverlight在调用wcf时,如果传递的参数长度大于8192字节,即8k,会提示Not Found错误。 解决方法如下: 1、wcf服务端修...

25580
来自专栏草根专栏

从头编写 asp.net core 2.0 web api 基础框架 (5) EF CRUD

Github源码地址:https://github.com/solenovex/Building-asp.net-core-2-web-api-starter-...

41860
来自专栏大内老A

Enterprise Library Policy Injection Application Block 之三:PIAB的扩展—创建自定义CallHandler(提供Source Code下载)

本系列的第一部分对PIAB使用场景进行了简单的介绍,作中阐述了通过PI(Policy Injection)的方式实现了Business Logic和Non-Bu...

354100
来自专栏菩提树下的杨过

c#:使用using关键字自动释放资源未必一定就会有明显好处

记录这篇文章的灵感来源来自今天下班前与同事的小小争论,我现在开发的一个项目中,有这样一段代码: public string ToXML() { ...

22980

扫码关注云+社区

领取腾讯云代金券