How to use a Singleton Signalr client within an MVC application

大城市里の小女人 提交于 2019-12-25 04:19:15

问题


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();


来源:https://stackoverflow.com/questions/21197274/how-to-use-a-singleton-signalr-client-within-an-mvc-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!