技术开发 频道

聚焦WCF行为的扩展

  WCF提供了四种类型的行为:服务行为、终结点行为、契约行为和操作行为。 这四种行为分别定义了四个接口:IServiceBehavior,IEndpointBehavior,IContractBehavior以及 IOperationBehavior。虽然是四个不同的接口,但它们的接口方法却基本相同,分别为 AddBindingParameters(),ApplyClientBehavior()以及ApplyDispatchBehavior()。注 意,IServiceBehavior由于只能作用在服务端,因此并不包含ApplyClientBehavior()方法。

  我们可以定义自己的类实现这些接口,但需要注意几点:
 
  1、行为的作用范围,可以用如下表格表示:

  2、可以利用自定义特性的方式添加扩展的服务行为、契约行为和操作行为,但不能添加终结点行为;可以利用配置文件添加扩展服务行为和终结点行为,但不能添加契约行为和操作行为。但这些扩展的行为都可以通过ServiceDescription添加。

  利用特性添加行为,意味着我们在定义自己的扩展行为时,可以将其派生自Attribute类,然后以特性方式添加。例如:

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface)]
public class MyServiceBehavior:Attribute, IServiceBehavior...
[MyServiceBehavior]
public interface IService...

  如果以配置文件的方式添加行为,则必须定义一个类继承自BehaviorExtensionElement(属于命名空间System.ServiceModel.Configuration),然后重写属性BehaviorType以及 CreateBehavior()方法。BehaviorType属性返回的是扩展行为的类型,而CreateBehavior()方法则负责创建该扩展 行为的对象实例:

public class MyBehaviorExtensionElement:BehaviorExtensionElement
    {
        
public MyBehaviorExtensionElement() { }
        
public override Type BehaviorType
        {
            
get { return typeof(MyServiceBehavior); }
        }

        
protected override object CreateBehavior()
        {
            
return new MyServiceBehavior();
        }
    }

  如果配置的Element添加了新的属性,则需要为新增的属性应用ConfigurationPropertyAttribute,例如:

[ConfigurationProperty("providerName",IsRequired = true)]
    
public virtual string ProviderName
    {
        
get
        {
            
return this["ProviderName"] as string;
        }
        
set
        {
            
this["ProviderName"] = value;
        }
    }

  配置文件中的配置方法如下所示:

<configuration>
  
<system.serviceModel>    
    
<services>
      
<service name="MessageInspectorDemo.Calculator">
        
<endpoint behaviorConfiguration="messageInspectorBehavior"
                  address
="http://localhost:801/Calculator"                  
                  binding
="basicHttpBinding"
                  contract
="MessageInspectorDemo.ICalculator"/>
      
</service>
    
</services>
    
<behaviors>
      
<serviceBehaviors>
        
<behavior name="messageInspectorBehavior">
          
<myBehaviorExtensionElement providerName="Test"/>
        
</behavior>
      
</serviceBehaviors>
    
</behaviors>
    
<extensions>
      
<behaviorExtensions>
        
<add name="myBehaviorExtensionElement"
             type
="MessageInspectorDemo.MyBehaviorExtensionElement, MessageInspectorDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
      
</behaviorExtensions>
    
</extensions>
  
</system.serviceModel>
</configuration>

  注意,在<serviceBehaviors>一节中,<behavior>下的<myBehaviorExtensionElement>就是我们扩展的行为,providerName则是 MyBehaviorExtensionElement增加的属性。如果扩展了IEndpointBehavior,则配置节的名称为<endpointBehaviors>。<extensions>节负责添加自定义行为的扩展。其 中,<add>中的name值与<behavior>下 的<myBehaviorExtensionElement>对应。

0
相关文章