How to use a Singleton Signalr client within an MV

2019-09-20 01:08发布

问题:

I have a need to use a .net client to connect to a Signalr enabled application.

The client class needs to be a singleton and loaded for use globally.

I want to know what is the best technique for using singletons globally within an MVC application.

I have been looking into using the application start to get the singleton, where I keep it is a mystery to me.

回答1:

The HUB cant be a singleton by design SignalR creates a instance for each incoming request.

On the client I would use a IoC framework and register the client as a Singleton, this way eachb module that tries to get it will get the same instance.

I have made a little lib that takes care of all this for you, install server like

Install-Package SignalR.EventAggregatorProxy

Read here for the few steps to hook it up, it needs a back plate service bus or event aggregator to be able to pickup your events

https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki

Once configured install the .NET client in your client project with

Install-Package SignalR.EventAggregatorProxy.Client.DotNet

See here how to set it up

https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki/.NET-Client

Once configured any class can register itself as a listener like

public class MyViewModel : IHandle<MyEvent>
{
   public MyViewModel(IEventAggregator eventAggregator) 
   {
      eventAggregator.Subscribe(this);
   }
   public void Handle(MyEvent message)
   {
      //Act on MyEvent
   }
}


回答2:

On the server you can send a message from outside the hub to all connected clients using the GetClients() method like this:

public MyHub : Hub 
{
    // (Your hub methods)

    public static IHubConnectionContext GetClients()
    {
        return GlobalHost.ConnectionManager.GetHubContext<MyHub>().Clients;
    }
} 

You can use it like this:

MyHub.GetClients().All.SomeMethod();