I have setup my signalR connection inside a singleton class so I can use the same connection throughout my entire project. The problem is that the connection never starts and the code never executes beyond the line await hubConnection.Start()
however when I do this outside the single class, then the connection is initiated in an instant. I wonder what I'm doing wrong.
Here's my definition of the singleton class:
public sealed class ProxySubscriber
{
private static volatile ProxySubscriber instance;
private static object syncRoot = new Object();
private IHubProxy chatHubProxy = null;
private HubConnection hubConnection = null;
public event Action<string, string> OnConnect;
private ProxySubscriber()
{
if (hubConnection == null) { hubConnection = new HubConnection("http://cforbeginners.com:901"); }
if (chatHubProxy == null) { chatHubProxy = hubConnection.CreateHubProxy("ChatHub"); }
chatHubProxy.On<string, string>("onConnected", (id, username) => OnConnect.Invoke(id, username));
}
private async Task<string> StartConnection()
{
await hubConnection.Start();
return "Connection started..";
}
public async void InvokeConnect()
{
await chatHubProxy.Invoke("Connect", "Mujtaba");
}
public static async Task<ProxySubscriber> GetInstance()
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new ProxySubscriber();
}
}
}
await instance.StartConnection();
return instance;
}
}
I'm using the singleton class like this:
ProxySubscriber proxySubscriber = ProxySubscriber.GetInstance().Result;
proxySubscriber.OnConnect += proxySubscriber_OnConnect;
proxySubscriber.InvokeConnect();