Search code examples
servicestacktopshelf

What's the proper way to host ServiceStack in a windows service?


I'm not using the HTTP functionality only the MQMessaging, so setting up my app host and listening on a port is not a requirement (at this time). I do want all the plumbing though that comes by default i.e. IoC ect.

Is this possible? FYI, I'm using Topshelf to bootstrap the service right now and it seems to work fine, I just don't need to be listening for HTTP requests.

Thank you, Stephen

public class Program
{
    public static void Main()
    {
        HostFactory.Run(x =>                                 
        {
            x.Service<AppHost>(s =>                        
            {
                s.ConstructUsing(name => new AppHost());    
                s.WhenStarted(ah =>
                {
                    ah.Init();
                    ah.Start("http://*:8088/");
                    "Lead message processor listening at http://localhost:8088 ".Print();
                });              
                s.WhenStopped(ah => ah.Stop());              
            });
            x.RunAsLocalSystem();

            x.SetDescription("Processes all messages for the Leads application.");
            x.SetDisplayName("Leads Message Processor");
            x.SetServiceName("LOLeadsProcessor");                      
        });
    }
}

public class AppHost : AppSelfHostBase
{
    public AppHost()
        : base("LO.Leads.Processor", typeof(HelloService).Assembly)
    {
        // Logging
        LogManager.LogFactory = new NLogFactory();
    }

    public override void Configure(Container container)
    {

        //RabbitMQ
        container.Register<IMessageService>(c => new RabbitMqServer("cdev-9010.example.com", "test", "test")
        {
            AutoReconnect = true,
            DisablePriorityQueues = true,

        }); 
        RabbitMqServer mqServer = (RabbitMqServer)container.Resolve<IMessageService>();


        mqServer.RegisterHandler<HelloIntro>(m =>
        {
            return new HelloIntroResponse { Result = "Hello, {0}!".Fmt(m.GetBody().Name) };
        });

        mqServer.Start();

    }
}

Solution

  • There's nothing special about hosting ServiceStack vs any other .NET App in a Windows Service which is ultimately a matter of preference. Here are a couple existing examples of ServiceStack Apps inside Windows Service on its own (i.e. without TopShelf):

    The self-hosting AppSelfHostBase is normally what Windows Service would inherit, but if you don't need to support HTTP Requests you can instead just inherit BasicAppHost or the common ServiceStackHost (which all ServiceStack Hosts inherit).