[WCF 学习笔记] 10. 行为控制

在完成服务契约设计和服务实现后,我们可以设置该服务的运行期行为(Behavior)。这些行为包括 Service Behaviors、Endpoint Behaviors、Contract Behaviors、Operation Behaviors。

有关所有行为的说明,可以查看 ms-help://MS.MSSDK.1033/MS.NETFX30SDK.1033/WCF_con/html/5c5450ea-6af1-4b75-a267-613d0ac54707.htm。

以下就常用的行为使用,做些演示。

ServiceBehaviorAttribute & OperationBehaviorAttribute

这是两个最常用的行为控制特性,可用于控制:
  • 服务对象生命周期。
  • 并发管理。
  • 异步通讯。
  • 配置文件参数。
  • 事务。
  • 元数据转换。
  • 会话(Session)周期。
  • 等等...
[ServiceContract]
public interface ICalculate
{
  [OperationContract]
  int Add(int a, int b);
}

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public class CalculateService : ICalculate
{
  public int Add(int a, int b)
  {
    Console.WriteLine(this.GetHashCode());
    return a + b;
  }
}

public class WcfTest
{
  public static void Test()
  {
    AppDomain.CreateDomain("Server").DoCallBack(delegate
    {
      ServiceHost host = new ServiceHost(typeof(CalculateService));
      host.AddServiceEndpoint(typeof(ICalculate), new WSHttpBinding(), "http://localhost:8080/calc");
      host.Open();
    });

    ChannelFactory<ICalculate> factory = new ChannelFactory<ICalculate>(new WSHttpBinding(), 
      "http://localhost:8080/calc");

    ICalculate o = factory.CreateChannel();
    Console.WriteLine(o.Add(1, 2));
    Console.WriteLine(o.Add(1, 2));

    factory.Close();
  }
}

输出:
30136159
3
41153804
3

ServiceMetadataBehavior

用于开启元数据获取功能。只有使用该行为,客户端才能通过 Svcutil.exe 或其他工具获取服务信息,进而生成客户端代理文件。
ServiceHost host = new ServiceHost(typeof(CalculateService));
host.AddServiceEndpoint(typeof(ICalculate), new BasicHttpBinding(), "http://localhost:8080/calc");

ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
behavior.HttpGetUrl = new Uri("http://localhost:8080/calc");
host.Description.Behaviors.Add(behavior);

host.Open();

ServiceDebugBehavior

开启调试功能,如将服务器端的异常信息直接传送给客户端。
ServiceHost host = new ServiceHost(typeof(CalculateService));
host.AddServiceEndpoint(typeof(ICalculate), new WSHttpBinding(), "http://localhost:8080/calc");
host.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
host.Open();

posted on 2008-11-06 13:20  topzengyi  阅读(129)  评论(0)    收藏  举报

导航