1
votes

I would like to be able to inject a SignalR hub into other classes as a dependency so I can send messages to it from server code (independently of a direct AJAX call from a Javascript client). Like this:

    private readonly IMyApplicationHub _signalHub;

    public HomeController(IMyApplicationHub signalHub)
    {
        _signalHub = signalHub;
    }

However, I don't how how to tell Autofac which instance of the hub to use - it doesn't seem to be the same instance that is created when a real client opens its connection.

I'm finding that, if I want to refer to the "real" hub instance that SignalR is using, I have to maintain my own Singleton reference and set it the first time that a method (in this case, Init) is invoked from a real Javascript client.

public class MyApplicationHub : Hub, IMyApplicationHub
{
    public static MyApplicationHub SingleInstance = null;

    public void Init(string message)
    {
        SingleInstance = this;
    }

    internal void SendMessage(string message, IEnumerable<LinkDto> links)
    {
        Clients.siteReceived(message);
    }
}

I must be missing something. Any assistance would be appreciated! (Eventually, I'd also like to know how to constructor-inject dependencies into the SignalR hub itself, but that seems like a slightly different problem.)

1
Can you post the registration? If you've already got a singleton that works, Autofac can inject it easily enough. - default.kramer
Why are you creating the instance of the hub within the controller? Just call the hub directly. - rball

1 Answers

4
votes

Do not create instances of the hub. The same way you're not supposed to create instances of the controller. The documentation shows you how to get an instance of the hub's clients outside of the hub.

Hubs are per call, equivalent to how controller in mvc are per request and you don't own the creation of them.