I'm looking for a clean way to have the ChannelFactory create channels for me with the ability to dispose them after use.
This is what I got:
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();
}
Is this a good solution?
Are there cleaner ways to do this?