我最近开始编写自己的 ChannelFactory 包装器来调用我的 WCF 服务,而不是依赖于 Visual Studio 自动生成的代码
以前,使用自动生成的代理,我可以这样做以进行错误检查:
protected AccessControlServiceClient AccessControlService
{
get
{
// Check if not initialized yet
if (HttpContext.Current.Session["AccessControlServiceClient"] == null)
HttpContext.Current.Session["AccessControlServiceClient"] = new AccessControlServiceClient();
// If current client is 'faulted' (due to some error), create a new instance.
var client = HttpContext.Current.Session["AccessControlServiceClient"] as AccessControlServiceClient;
if (client.State == CommunicationState.Faulted)
{
try { client.Abort(); }
catch { /* no action */ }
client = new AccessControlServiceClient();
HttpContext.Current.Session["AccessControlServiceClient"] = client;
}
return client;
}
}
我应该如何为 ChannelFactor 处理这个问题?如果出现问题,处理和重新创建频道的最佳做法是什么?例如,间歇性网络连接、会话超时等。
这是我的代码目前的样子:
来自 ProxyBase.cs 的片段 - 创建通道
private void Initialise()
{
lock (_sync)
{
if (_channel != null) return;
_channel = new ChannelFactory<T>(_serviceEndPointUri).CreateChannel();
}
}
UserManagementServiceClient.cs - IUserManagementService 是 WCF 合同
public class UserManagementServiceClient : ProxyBase<IUserManagementService>
{
public UserManagementServiceClient(string serviceEndPointUri)
: base(serviceEndPointUri)
{
}
public TokenResponse GetToken(TokenRequest request)
{
return Channel.GetToken(request);
}
public LoginResponse Login(LoginRequest request)
{
return Channel.Login(request);
}
public LogoutResponse Logout(LogoutRequest request)
{
return Channel.Logout(request);
}
}
最后,这就是我在 MVC 项目中的调用方式
protected UserManagementServiceClient UserManagementService
{
get
{
// Check if not initialized yet
if (HttpContext.Current.Session["UserManagementServiceClient"] == null)
HttpContext.Current.Session["UserManagementServiceClient"] = new UserManagementServiceClient("NetTcpBinding_UserManagementService");
var client = HttpContext.Current.Session["UserManagementServiceClient"] as UserManagementServiceClient;
return client;
}
}
所以目前,每当默认的 10 分钟会话结束时,我都会收到错误消息,因为通道已经关闭。
如何强化我的代码,以便处理网络断开/会话超时等问题?