I have some information that needs to be displayed to users in real-time. Before I had repetitive calls to the server for a fresh data.
Now I am thinking to replace these repetitive calls with SignalR. General idea is to subscribe on the client to the hub which will send updates to all clients when new entry will be added to a database, however I stuck there with general design of that structure.
So I have my WebAPI project and service layer. In the service when new entry is added I am going to raise an event and inside hub catch that event and send updates to all clients.
Is it a right way how these kind things achieved with SignalR? Can somebody explain how I can implement that given that I am using asp.net WebAPI and SimpleInjector.
PubSub patterns with signalR could be realized natively using groups. Using the group name as topic, users can subscribe\\unsubscribe by joining\\leaving the group.
Here is the code snippets. It is straight forward and it should scale out well.
[HubName("PubSub")]
public class PubSubHub : Hub {
public void Publish(string topic, object data) {
Clients.Group(topic).onNewMsg(topic, data);
}
public async Task Subscribe(string topic) {
await Groups.Add(Context.ConnectionId, topic);
Clients.Client(Context.ConnectionId).onSubscribed(topic);
}
public async Task Unsubscribe(string topic) {
await Groups.Remove(Context.ConnectionId, topic);
Clients.Client(Context.ConnectionId).onUnsubscribed(topic);
}
}
There are lots of ways of designing pub / sub around SignalR
I created a wrapper for SignalR to solve it in a Event aggregation form
Please see the wiki
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki
Install using nuget
Install-Package SignalR.EventAggregatorProxy
See the demo project https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/tree/master/SignalR.EventAggregatorProxy.Demo.MVC4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.