gpt4 book ai didi

c# - 处置由 WCF ChannelFactory 创建的 Channel

转载 作者:太空狗 更新时间:2023-10-29 18:29:26 25 4
gpt4 key购买 nike

我正在寻找一种干净的方式ChannelFactory 为我创建 channel ,并在使用后能够处理它们。< br/>这是我得到的:

public class ClientFactory : IClientFactory
{
private const string endpointName = "IMyService";
private readonly ChannelFactory<IMyService> _factory;

public ClientFactory()
{
_factory = new ChannelFactory<IMyService>(endpointName);
}

public Client<IMyService> GetClient()
{
IMyService channel = _factory.CreateChannel();
return new Client<IMyService>(channel);
}
}

public class Client<T> : IDisposable
{
public T Channel { get; private set; }

public Client(T channel)
{
if (channel == null)
throw new ArgumentException("channel");

Channel = channel;
}

public void Dispose()
{
(Channel as IDisposable).Dispose();
}
}

//usage
using (var client = _serviceFactory.GetClient())
{
client.Channel.DoStuff();
}

这是一个好的解决方案吗?
有没有更简洁的方法来做到这一点?

最佳答案

不,没有更干净的方式来包装 channel 。

另一种方法是改用 Action/Func。它不是更干净,但可能更适合您的应用程序。

我是这样做的:

internal class WrappedClient<T, TResult> : IDisposable
{
private readonly ChannelFactory<T> _factory;
private readonly object _channelLock = new object();
private T _wrappedChannel;

public WrappedClient(ChannelFactory<T> factory)
{
_factory = factory;
}

protected T WrappedChannel
{
get
{
lock (_channelLock)
{
if (!Equals(_wrappedChannel, default(T)))
{
var state = ((ICommunicationObject)_wrappedChannel).State;
if (state == CommunicationState.Faulted)
{
// channel has been faulted, we want to create a new one so clear it
_wrappedChannel = default(T);
}
}

if (Equals(_wrappedChannel, default(T)))
{
_wrappedChannel = _factory.CreateChannel();
}
}

return _wrappedChannel;
}
}

public TResult Invoke(Func<T, TResult> func)
{
try
{
return func(WrappedChannel);
}
catch (FaultException)
{
throw;
}
catch (CommunicationException)
{
// maybe retry works
return func(WrappedChannel);
}
}

protected virtual void Dispose(bool disposing)
{
if (!disposing ||
Equals(_wrappedChannel, default(T)))
return;

var channel = _wrappedChannel as ICommunicationObject;
_wrappedChannel = default(T);
try
{
channel.Close();
}
catch (CommunicationException)
{
channel.Abort();
}
catch (TimeoutException)
{
channel.Abort();
}
}

public void Dispose()
{
Dispose(true);
}
}

然后你像这样使用服务

client.Invoke(channel => channel.DoStuff())

关于c# - 处置由 WCF ChannelFactory 创建的 Channel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15223298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com