SignalR Self Hosting in a Windows Service

This blog provides a simple template or example of a windows service which hosts a SignalR service.

Code: https://github.com/damienbod/SignalRWSelfHostingWindowsServiceTemplate

The Start and Stop methods used by the Windows Service use a long running Task which can be cancelled. SignalR is self hosted in OWIN.

using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Hosting;
using Owin;
using SignalREngine;

[assembly: OwinStartup(typeof(Startup))]

namespace SignalREngine
{
    public class Startup
    {
        static CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

        // Your startup logic
        public static void StartServer()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            Task.Factory.StartNew(RunSignalRServer, TaskCreationOptions.LongRunning
                                  , cancellationTokenSource.Token);  
        }

        private static void RunSignalRServer(object task)
        {
            string url = "http://localhost:8089";
            WebApp.Start(url);
        }

        public static void StopServer()
        {
            _cancellationTokenSource.Cancel();
        }

        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder app)
        {
            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                };

                hubConfiguration.EnableDetailedErrors = true;
                map.RunSignalR(hubConfiguration);
            });
        }
    }
}

The main method of the service just starts the service. If you want to debug using a console application, just comment out the ServiceBase method and provide an command line argument.

using System;
using System.ServiceProcess;
using SignalREngine;

namespace SignalREngineServiceWindowsService
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            // Remove this if you want to test as a console application and add an arg
			ServiceBase.Run(new SignalREngineServiceWindowsService());

            if (args != null)
            {
                try
                {
                    Startup.StartServer();
                    Console.ReadKey();
                }
                finally
                {
                    Startup.StopServer();
                }
            }
        }
    }
}

The Windows service then calls the Start/Stop methods (SignalREngineServiceWindowsService):

protected override void OnStart(string[] args)
{
  Startup.StartServer();
  base.OnStart(args);
}

protected override void OnStop()
{
  Startup.StopServer();
  base.OnStop();
}

Install and uninstall batch files are provided for the application. These install and start the service or removes it from your computer. The path needs to be changed if you want to install it on your PC. Start the install script direct from your bin directory.

Once installed, the SignalR Hub will run and can be started or stopped using the window service menu (services.msc)
SignalRService01

A Test WPF client has been provided to test the SignalR Hub in the service.
.\SignalRClientWPF\SignalRClientWPF\bin\Debug\SignalRClientWPF.exe

SignalRService02

Now all you have to do is add your Hub with proper exception handling… (And off course remove the demo Hub)

Links:

http://www.asp.net/signalr

9 comments

  1. Hi, is possible to self host one application with MVC and Web?

    1. Hi, thanks for you comment.

      You can host SignalR or Web API in any .NET application/process as it uses OWIN. The MVC application runs on IIS. So you could run MVC and SignalR together on the IIS, if you want.

      greetings Damien

      1. Thanks fot attention, there is no way to self host a MVC application?

      2. Not till MVC 6, vNext
        greetings Damien

  2. Martin · · Reply

    Hi, Using your WPF sample app (after installing the service) when I press “Add Message” I get the exception “Data cannot be sent because the connection is in the disconnected state. Call start before sending any data.” Any ideas? thanks Martin

    1. Hi Martin

      Is the service running?

      You need to include the line ServiceBase.Run(new SignalREngineServiceWindowsService());

      I have commented this out in the program.cs file. Then it will run as a service.

      Hope this helps

      Greetings Damien

  3. Martin · · Reply

    Thanks for quick reply. Yes the service is started and running. The line “ServiceBase.Run(new SignalREngineServiceWindowsService());” is there also. The error is happening in the WPF client sample app. Looks like it cant see the service or something. Wondering if its firewalls, security or something machine specific.

  4. et’s say server is disconnected and then connected again, how to reconnect client to it? In signalRClientWPF i dont see any line does that.

    1. Hi Robert, sorry for slow answer, busy, the WPF client doesn’t have any exception handling implemented.

      Greetings Damien

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: