Making SignalR Hub Strongly Typed

Learn to make SignalR Hub strongly typed.

We'll cover the following

Problem

So far, when we’ve been calling clients from the hub, we've used just a normal string to specify the client-side event name that needs to be triggered. But the problem with using a string is that it can contain any arbitrary text. If we misspell the name, the code will not warn us. Perhaps, it’s not a big problem in our case because we only have one such call, so it’s easy to manage. But what if we had a complex Hub (or multiple Hubs) with many of such calls?

Solution

Fortunately, there is a solution. We can make our Hub strongly typed, so any method we have on the client can be transformed into a C# method representation. And we can’t misspell a name of a C# method. Our IDE will show an error, and our code won’t compile

Fortunately, there's a solution. We can make our Hub strongly typed, so any method we have on the client can be transformed into a C# method representation. And we can’t misspell a name of a C# method. Our IDE will show an error, and our code won’t compile.

To do so, we'll need to add an interface that represents the client’s events. Then, we will enforce this interface on the Hub. We'll start by adding the ILearningHubClient.cs file to the root folder of our project. This file will contain the following content:

Get hands-on with 1200+ tech skills courses.