Search code examples
signalrsignalr-hub

SignalR and Hub Persistance


I am trying out SignalR, and i don't quite understand how to call methods from my client in a way that it calls the same hub.

i have two methods in my hub:

    private ctlDataManager myManager;
    public void StartConnection()
    {
        myManager = new ctlDataManager("test");

        myManager.UpdateItemEvent += myManager_UpdateItemEvent;

        myManager.Connect();
    }

    public void StopConnection()
    {
        myManager.Disconnect();
    }

And in my client i try to call them like this:

var notificationHub = $.connection.notificationHub;

    $.connection.hub.start()
        .done(function (state) {
            $("#submit").click(function (e) {
                e.preventDefault();
                notificationHub.server.startConnection();
                return false;
            });

            $("#stop").click(function (e) {
                e.preventDefault();
                notificationHub.server.stopConnection();
                return false;
            });
        });

Now when i click on the start button it works fine it starts it and receives data too. But when i click the stop button it throws an instance of an object error. It appears that 'myManager' is null. It's almost as a new hub were open. Naturally i need it to be the same one as i need to close the connection. How can i do that?


Solution

  • From my understanding, the server-side hub class is not persisted. Therefore, the myManager object is created with each method call from a client. My advice would be to declare myManager elsewhere in your application that you can assure 100% up-time, and have your server-side hub methods communicate with it that way.

    One way for you to verify this is to debug the constructor of your hub class. You will notice that it is called for every client->server-side method call.