I have a look at many examples on several web pages and finally getting very confused due to the different approach on each of the examples. I simply want to use a HubBase class where I define shared hub methods i.e. OnConnected(), AddToGroup()) and multiple hub classes (HubX, HubY) where I define specific methods to these hubs. Here is the basic structure I try to apply:
ITypedHubClient:
public interface ITypedHubClient
{
Task BroadcastData(string groupName, object data);
}
HubBase:
public class HubBase : Hub<ITypedHubClient>
{
public readonly static ConnectionMapping<string> connections =
new ConnectionMapping<string>();
public override async Task OnConnected()
{
//
}
public override async Task OnDisconnected(bool stopCalled)
{
//
}
public async Task AddToGroup(string connectionId, string groupName)
{
//
}
public async Task SendMessageToAll(string user, string message)
{
await Clients.All.SendAsync(user, message);
}
public async Task SendMessageToGroup(string groupName, string message)
{
await Clients.Group(groupName).SendAsync(message);
}
}
HubX:
[HubName("hubX")]
public class HubX : HubBase
{
private readonly static IHubContext context =
GlobalHost.ConnectionManager.GetHubContext<HubX>();
public static async Task SendDataToGroup(string groupName, object data)
{
await context.Clients.Group(groupName).refreshData(data);
}
public static async Task BroadcastData(object data)
{
await context.Clients.Group("groupX").refreshData(data);
}
}
Controller:
public class MyController : Controller
private IHubContext<HubX> hubContext;
public MyController(IHubContext<HubX> hubContext)
{
this.hubContext = hubContext;
}
public JsonResult Create()
{
//...
this.hubContext.Clients.Group("groupX").BroadcastData("groupX", data);
}
My question is that:
1) What changes should be made in order to use DI and use base Hub class properly?
2) Should I call the hub methods from Controller? Or Hub class (HubX, Y)? I mean that in some examples, hubContext.Clients.All.SendMessageToAll(message)
methods are called from the Controller directly while in some of them calls the method in the Hub class i.e. HubX.SendMessageToAll(message);
. Any idea about which one is best practice?
3) Should I inherit Hub from Hub or HubBase class?
Note: If you have idea only one of the questions above, it is also ok for me and any help would be appreciated.