我的 WCF 客户端库有以下计划架构:
- 使用 ChannelFactory 而不是 svcutil 生成的代理,因为我需要更多控制,而且我想将客户端保留在单独的程序集中并避免在我的 WCF 服务更改时重新生成
- 需要将带有消息检查器的行为应用于我的 WCF 端点,因此每个通道都能够发送自己的身份验证令牌
- 我的客户端库将从 MVC 前端使用,所以我必须考虑可能的线程问题
- 我正在使用 .NET 4.5(也许它有一些帮助程序或新方法可以以更好的方式实现 WCF 客户端?)
我已经阅读了许多关于各种不同位的文章,但我仍然对如何以正确的方式将它们组合在一起感到困惑。我有以下问题:
- 据我了解,建议将 ChannelFactory 缓存在静态变量中,然后从中获取通道,对吗?
- 端点行为是特定于整个 ChannelFactory 还是我可以分别为每个通道应用我的身份验证行为?如果行为特定于整个工厂,这意味着我不能在端点行为对象中保留任何状态信息,因为相同的身份验证令牌将被每个通道重用,但显然我希望每个通道都有自己的身份验证令牌当前用户。这意味着,我必须在我的端点行为中计算令牌(我可以将它保存在 HttpContext 中,我的消息检查器行为只会将它添加到传出消息中)。
- 我的客户端类是一次性的(实现 IDispose)。我如何正确处置通道,知道它可能处于任何可能的状态(未打开、打开、失败......)?我只是丢弃它吗?我要中止它然后丢弃吗?我要关闭它(但它可能根本还没有打开)然后丢弃吗?
- 如果在使用频道时遇到问题怎么办?是只有通道坏了还是整个 ChannelFactory 坏了?
我猜,一行代码说一千多个单词,所以这是我的代码形式的想法。我已经用“???”标记了我上面的所有问题 在代码中。
public class MyServiceClient : IDisposable
{
// channel factory cache
private static ChannelFactory<IMyService> _factory;
private static object _lock = new object();
private IMyService _client = null;
private bool _isDisposed = false;
/// <summary>
/// Creates a channel for the service
/// </summary>
public MyServiceClient()
{
lock (_lock)
{
if (_factory == null)
{
// ... set up custom bindings here and get some config values
var endpoint = new EndpointAddress(myServiceUrl);
_factory = new ChannelFactory<IMyService>(binding, endpoint);
// ???? do I add my auth behavior for entire ChannelFactory
// or I can apply it for individual channels when I create them?
}
}
_client = _factory.CreateChannel();
}
public string MyMethod()
{
RequireClientInWorkingState();
try
{
return _client.MyMethod();
}
catch
{
RecoverFromChannelFailure();
throw;
}
}
private void RequireClientInWorkingState()
{
if (_isDisposed)
throw new InvalidOperationException("This client was disposed. Create a new one.");
// ??? is it enough to check for CommunicationState.Opened && Created?
if (state != CommunicationState.Created && state != CommunicationState.Opened)
throw new InvalidOperationException("The client channel is not ready to work. Create a new one.");
}
private void RecoverFromChannelFailure()
{
// ??? is it the best way to check if there was a problem with the channel?
if (((IChannel)_client).State != CommunicationState.Opened)
{
// ??? is it safe to call Abort? won't it throw?
((IChannel)_client).Abort();
}
// ??? and what about ChannelFactory?
// will it still be able to create channels or it also might be broken and must be thrown away?
// In that case, how do I clean up ChannelFactory correctly before creating a new one?
}
#region IDisposable
public void Dispose()
{
// ??? is it how to free the channel correctly?
// I've heard, broken channels might throw when closing
// ??? what if it is not opened yet?
// ??? what if it is in fault state?
try
{
((IChannel)_client).Close();
}
catch
{
((IChannel)_client).Abort();
}
((IDisposable)_client).Dispose();
_client = null;
_isDisposed = true;
}
#endregion
}