连接的超时时间可以在域服务端点的客户端上设置。但是如何掌握呢?通过为域上下文创建扩展方法:
public static class DomainServiceExtensions
{
/// <summary>
/// This method changes the send timeout for the specified
/// <see cref="DomainContext"/> to the specifified <see cref="TimeSpan"/>.
/// </summary>
/// <param name="domainContext">
/// The <see cref="DomainContext"/> that is to be modified.
/// </param>
/// <param name="newTimeout">The new timeout value.</param>
public static void ChangeTimeout(this DomainContext domainContext,
TimeSpan newTimeout)
{
// Try to get the channel factory property from the domain client
// of the domain context. In case that this property does not exist
// we throw an invalid operation exception.
var channelFactoryProperty = domainContext.DomainClient.GetType().GetProperty("ChannelFactory");
if(channelFactoryProperty == null)
{
throw new InvalidOperationException("The 'ChannelFactory' property on the DomainClient does not exist.");
}
// Now get the channel factory from the domain client and set the
// new timeout to the binding of the service endpoint.
var factory = (ChannelFactory)channelFactoryProperty.GetValue(domainContext.DomainClient, null);
factory.Endpoint.Binding.SendTimeout = newTimeout;
}
}
有趣的问题是何时调用此方法。一旦端点在使用中,就不能再更改超时。所以在创建域上下文后立即设置超时:
DomainContext
-class 本身是,但幸运的sealed
是,该类也被标记为partial
- ,这种方法OnCreated()
可以很容易地扩展。
public partial class MyDomainContext
{
partial void OnCreated()
{
this.ChangeTimeout(new TimeSpan(0,10,0));
}
}
专业提示:在实现部分类时,类的所有部分的名称空间必须相同。此处列出的代码属于客户端项目(例如使用命名空间RIAServicesExample
),但上面显示的部分类需要驻留在服务器端命名空间中(例如RIAServicesExample.Web
)。