Reputation:
In my Angular project use TypedHub interface (called IDemoHubTypedClient) in my project as shown below:
IDemoHubTypedClient:
public interface IDemoHubTypedClient
{
Task BroadcastData(object data);
Task SendMessageToClient(string title, string name, string message);
}
However, as I inherited from Hub<IDemoHubTypedClient>
instead of Hub
, I cannot access to the default hub methods i.e. SendAsync()
as shown below and only access the methods in the IDemoHubTypedClient
i.e. BroadcastData()
and SendMessageToClient()
. As I need to use this structure for using DI and TypedHub, how can I fix this problem? Should I add all the hub methods (SendAsync()
etc.) in my IDemoHubTypedClient
? As you know there is only seals of these methods as they are on client side (I call BroadcastData()
method and this method is actually on client side). Any idea?
DemoHub:
public class DemoHub : Hub<IDemoHubTypedClient>
{
public async Task SendMessageToAll(string user, string message)
{
await Clients.All.SendAsync(user, message);
}
}
Upvotes: 0
Views: 789
Reputation: 2666
I think you must define all your client methods on the interface if you want to use strongly typed hub. AFAIK there is no way to "mix-and-match" between a strongly typed hub and a normal hub. If you have a client like this:
this.connection.on('receiveMessage', (message: string) => {
// Do things
});
this.connection.on('receiveData', (data: MyData, message: string) => {
// Do things
});
Then if you want to use strongly typed hub, you must define your strongly typed hub interface with methods using the same names and signatures (method names are case-insensitive):
public interface IDemoClient
{
Task ReceiveMessage(string message);
Task ReceiveData(MyData data, string message);
}
The advantage is that you can write await Clients.All.ReceiveMessage("Hello from server!")
instead of await Clients.All.SendAsync("ReceiveMessage", "Hello from server!")
. The whole point is that you don't have to hardcode the client method name and you get additional static type checking for the method parameters.
Upvotes: 1
Reputation: 3431
It's not that easy. You need to ha a SignalR ConnectionManager ready (dependency injection), and get a typed HubContext from there, and then you can access the given Hub's functions. See more here: https://codeopinion.com/practical-asp-net-core-hubcontext/
Upvotes: 0