namespace StockSharp.Community
{
using System;
using System.ServiceModel;
using Ecng.Common;
using Ecng.Net;
///
/// The base client for access to the WCF services.
///
/// WCF service type.
public abstract class BaseServiceClient : Disposable
where TService : class
{
private readonly string _endpointName;
private readonly bool _hasCallbacks;
private TService _service;
private ChannelFactory _factory;
///
/// Initialize .
///
/// Server address.
/// The access point name in the configuration file.
/// Whether the has events.
protected BaseServiceClient(Uri address, string endpointName, bool hasCallbacks = false)
{
if (address == null)
throw new ArgumentNullException("address");
Address = address;
_endpointName = endpointName;
_hasCallbacks = hasCallbacks;
}
///
/// Server address.
///
public Uri Address { get; private set; }
///
/// Whether the connection has been established.
///
public bool IsConnected { get; private set; }
///
/// Create WCF channel.
///
/// WCF channel.
protected virtual ChannelFactory CreateChannel()
{
return new ChannelFactory(new WSHttpBinding { Security = { Mode = SecurityMode.None }, UseDefaultWebProxy = true }, new EndpointAddress(Address));
}
///
/// To connect. The connection is established automatically when the method or is called.
///
public virtual void Connect()
{
_factory = ChannelHelper.Create(_endpointName, CreateChannel);
if (_hasCallbacks)
_service = _factory.CreateChannel();
OnConnect();
IsConnected = true;
}
///
/// Connect.
///
protected virtual void OnConnect()
{
}
///
/// To call the service method.
///
/// The result type returning the service method.
/// The handler in which the method is called.
/// The result returning the service method.
protected virtual TResult Invoke(Func handler)
{
if (handler == null)
throw new ArgumentNullException("handler");
if (!IsConnected)
Connect();
return _hasCallbacks ? handler(_service) : _factory.Invoke(handler);
}
///
/// To call the service method.
///
/// The handler in which the method is called.
protected void Invoke(Action handler)
{
if (handler == null)
throw new ArgumentNullException("handler");
Invoke