This is the last one of the series I’ve planned about SignalR, this time I’ll demonstrate how can we migrate the SignalR system that we previously created to a self hosted server and in that way have a very light weight server application that will have all the functionalities that we need and nothing more than that. The point is to get the exact same behavior of the server as we had it when we build it with WebAPI2.
Photo Credit Code Project
In a case you missed the first two posts please review them here
Part1: SignalR, what is happening under the hood
Part 2: How to build chat server and client with SignalR and ASP.NET WebAPI 2
Create the self hosted server
First step we need to do is create a console application that will actually be our self hosted server that will handle our SignalR calls.
Next step is to add self hosted libraries from NuGet.
PM> Install-Package Microsoft.AspNet.SignalR.SelfHost
After executing that command will have all the needed libraries installed. Also we’ll need to install libraries for cross domain support.
PM> Install-Package Microsoft.Owin.Cors
And that is all we need to do and now we have all the weapons that we need to create the self hosted server.
Migrating from WebAPI 2 to Self Hosted app
From now on all we need to do for this implementation is to copy-paste some code from the Web API project. First we need to copy-paste the Startup class. Note that it needs to be put in the “root” namespace of the project.
Note that we have removed configuration code that is specific for Web API.
Next step we need to do is to copy the hubs (in our sample we have only one), we are going to keep the same folder structure just have in mind to change the namespace to match this project.
There is a small update in the message that we are sending, I’ve added “[Self Hosted Server]” in the string just to make differentiation from the messages of IIS hosted Web API server.
Now there is one more thing that we need to do in order to run the server. In the Main method we are adding this code and specifying the url.
We’ve added one ReadLine because we want the Console app not finish execution.
And that is it. Now we have a fully operating self hosted lightweight server. Let’s try it to see if everything is working properly. When we are starting the app we are getting this output
So far everything looks OK.
Let’s change the url of our client to point to the self hosted server. We can do that in chatClient.js
If we run the client and open couple of instanced we are getting this.
Aaaand it’s working!!!
So you saw how easy is to make the migration to a self hosted app and get really portable light weight server that will handle our SignalR calls instead of using the robust and heavy Web API/IIS infrastructure.
The updates are pushed to GitHib so you can try them and experiment with those if you like.