Asp.net Core with SignalR server and Autofac

SignalR server for asp.net core is currently in version 0.2.0. It has not been released yet to the official nuget repositories, so we must configure our project to use the asp.net core dev feed to obtain SignalR related packages.
Autofac for asp.net core still does not have the hubs registration extensions that we are used to when using full framework packages, but we will see how we can write them from scratch.

First of all we create a new asp.net core web project and we create a NuGet.config file so we can specify the core devevelopment NuGet feed so we can restore the websockets and SignalR packages.

The NuGet.config file should look like this:

Once created the nuget file, we should add the dependencies to project.json. The dependencies to use SignalR and autofac are shown below:

 

We are now set to start configuring our hubs!. As an example we are going to create a ChatHub that will receive a service to keep track of connections in it’s constructor.

Let’s create first the service interface and implementation to register it with AutoFac:
IHubTrackingService.cs

 

HubTrackingService.cs

 

The HubTrack class is a POCO class with the following properties, just as an example:
HubTrack.cs

 

Now we are ready to create our ChatHub injecting in the constructor the HubTrackingService to allow tracking clients with OnConnected Method:

ChatHub.cs

 

Now, it is time to configure our Startup.cs to add SignalR Server and dependency injection.
In full framework, we use the RegisterHubs autofac extesion to register our hub classes:

but it is not available yet in Autofac for asp.net core so we should write a ContainerBuilder Extension to do this for us, the code is shown below:

AutofacExtensions.cs

Note: We use ExternallyOwned() to allow SignalR disposing the Hubs instead of being managed by Autofac.

Once our extension is added to the project we should set our Configure and ConfigureServices methods in Startup.cs

 

Startup.cs

Notice the line:

 

In asp.net core we don’t have Assembly.GetExecutingAssembly() so we get the assembly from the Startup.cs type
How do we use the Hubs to notify clients when execution is inside a Mvc/Api Controller?

If we are working inside a controller, we can also notify the clients that are connected to a hub injecting the SignalR IConnectionManager interface. We just need to get the context using the hub target type we want to invoke and perform the client operation.

Imagine we have a TicketController, where Tickets can be added through a POST action and we want to notify all clients connected to the NotificationHub about the ticket being added, we could do it like this:

 

And we are done!. We can now use SignalR in our Asp.Net Core project using Autofac dependency injection.

 

Happing coding!.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *