自定义WCF RIA Services 超时时间

一般的WCF服务可以通过设置配置文件中Timeout属性值来自定义服务的超时时间,但WCF服务没有配置文件,默认的超时是60s。但有时候,我们的查询时间超过60s,我们能不能通过自己来定义超时时间呢。

答案是肯定的。RIA Services生成的代理类刚好是部分(partial)类,我们可以利用这一点来设置超时。

先在Service项目中建一个类:WcfTimeoutUtility,这里设置超时方法

/// <summary>
  /// Utility class for changing a domain context's WCF endpoint's
  /// SendTimeout. 
  /// </summary>
  public static class WcfTimeoutUtility
  {
    /// <summary>
    /// Changes the WCF endpoint SendTimeout for the specified domain
    /// context. 
    /// </summary>
    /// <param name="context">The domain context to modify.</param>
    /// <param name="sendTimeout">The new timeout value.</param>
    public static void ChangeWcfSendTimeout(DomainContext context, 
                                            TimeSpan sendTimeout)
    {
      PropertyInfo channelFactoryProperty =
        context.DomainClient.GetType().GetProperty("ChannelFactory");
      if (channelFactoryProperty == null)
      {
        throw new InvalidOperationException(
          "There is no 'ChannelFactory' property on the DomainClient.");
      }

      ChannelFactory factory = (ChannelFactory)
        channelFactoryProperty.GetValue(context.DomainClient, null);
      factory.Endpoint.Binding.SendTimeout = sendTimeout;
    }
  }

通过部分类的特性,来改变默认的时间。

注意,这里的类名:MyDomainContext要与你Service中自动生成的代码中的DomainContext类名一样,而且命名空间也应该也web.g.cs中DomainContext类一致。

public partial class MyDomainContext
  {
    partial void OnCreated()
    {
      TimeSpan tenMinutes = new TimeSpan(0, 10, 0);
      WcfTimeoutUtility.ChangeWcfSendTimeout(this, tenMinutes);
    }
  }

 

posted @ 2013-04-18 22:43  Gyoung  阅读(3224)  评论(10编辑  收藏  举报