// 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; using GBase.Client.Interfaces; namespace GBase.Client.Services { /// /// Base class for services of the /// /// The of the inheriting service public abstract class Service : IAsyncDisposable { /// /// Base class for services of the /// /// The /// The endpoint for this protected Service(ServerProtocol serverProtocol, string endpoint) { ServiceFactory = OpenFactory(serverProtocol, endpoint); } /// /// The for this /// private ChannelFactory ServiceFactory { get; } /// /// Open a for the given and endpoint /// /// The /// The endpoint for this /// 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; } /// /// Open an for this /// /// The opened channel of type protected TService OpenChannel() { TService channel = ServiceFactory.CreateChannel(); ((IClientChannel)channel).Open(); return channel; } /// /// Close the for a given /// /// The protected void CloseChannel(TService service) { ((IClientChannel) service).Close(); } /// /// Dispose used resources asynchronously /// /// A to await public async ValueTask DisposeAsync() { ServiceFactory.Close(); } } }