Self Hosting SignalR
Self Hosting SignalR
SignalR, as shown in the earlier posts, can be hosted within a regular ASP.NET application
(in other words, on IIS), but can also be self-hosted. You may want to do so if you don’t
want the SignalR hosting machine to have IIS installed. In this post I’ll show a simple way
of doing so with a console application. It won’t be much different with windows service
and I’ll explain how to do it there as well.
Step 1: Install Nuget packages
There are two nuget packages that you need to install:
These three packages will install also the OWIN package (dependency of all three packages),
Microsoft.Aspet.SignalR.Core (dependency of Microsoft.AspNet.SignalR.Owin) and
Newtonsoft.Json (dependency of Microsoft.Aspet.SignalR.Core).
Step 2: Write your Hub / Connection code
In here, there is no difference between the hosting environments.You may find example on
some previous signalR posts.
Step 3: Start your Host
To start your host, use the Microsoft.Owin.Hosting.WebApplication class from Microsoft.Owin.Hosting
assembly. This class has static method named Start. This method has 3 overloads, we will use the generic
one and give it a custom class as type parameter. This class should contain a method named Configuration
that expects IAppBuilder as a parameter. This parameter will be supplied by the Start method of
This is how the method call should look like:
Console.WriteLine("Server is running, Press <Enter> to stop");
The Start method will use the url parameter, call the Configuration method of
MyStartUp class and returna Disposable object. All we have to do here is wait
for some user action and until that don’t leave the using block,
so the Dispose method won’t get called.
In real-life you might use windows service to host SignalR. If so, you may use a
private IDisposable member on the service class. on the OnStart method of the
windows service call the Start method initializing the IDisposable member
with its return value, and calling its Dispose method on the OnStop or Dispose
method of the service class.
Now, let’s look at MyStartup class
internal class MyStartUp
public void Configuration(IAppBuilder app)
You can see above the call for MapHub method , very similar to the call we
make in ASP.NET application, on Global.asax file. However It is not the same
method. This method comes from Owin.OwinExtensions
Step 4: Consume
Your SignalR server is up and running, you may consume it’s services in any way you like.
No difference between the fact that it is hosted in a self hosting environment and not IIS.
Self- hosting SignalR is easy. Hosting it on a windows service comes with the regular
”headache’ of any windows service however the SignalR code itself almost looks the same.
Update: I’d just realized that I’ve copied the wrong namespace of
System.Runtime.CompilerServices instead of Owin on step 4.
Thanks @davidfowl for correction.