// Author: Gockner, Simon // Created: 2020-02-11 // Copyright(c) 2020 SimonG. All Rights Reserved. using System; using System.ServiceModel; using System.Threading.Tasks; using GBase.Api.Communication; namespace GBase.Client.Services { public abstract class Service : IAsyncDisposable { protected Service(ServerProtocol serverProtocol, string endpoint) { ServiceFactory = OpenFactory(serverProtocol, endpoint); } private ChannelFactory ServiceFactory { get; } private ChannelFactory OpenFactory(ServerProtocol serverProtocol, string endpoint) { ChannelFactory factory; if (serverProtocol == ServerProtocol.Http) factory = new ChannelFactory(new BasicHttpBinding(), new EndpointAddress(endpoint)); else if (serverProtocol == ServerProtocol.Tcp) factory = new ChannelFactory(new NetTcpBinding(), new EndpointAddress(endpoint)); //TODO: Set security mode here? else throw new ArgumentOutOfRangeException(nameof(serverProtocol), serverProtocol, "Invalid server protocol used."); factory.Open(); return factory; } protected TService OpenChannel() { TService channel = ServiceFactory.CreateChannel(); ((IClientChannel)channel).Open(); return channel; } protected void CloseChannel(TService service) { ((IClientChannel) service).Close(); } public async ValueTask DisposeAsync() { ServiceFactory.Close(); } } }