Skip to content

Self hosting ServiceStack service (RabbitMQ callable)

Sunny Ahuwanya edited this page Jan 27, 2016 · 11 revisions

Using RestBus with a self hosted service stack service is straightforward.

Create a new Console Application, which will serve as the service and install the RestBus.RabbitMQ and RestBus.ServiceStack NuGet packages.

PM> Install-Package RestBus.RabbitMQ
PM> Install-Package RestBus.ServiceStack

Create the ServiceStack self hosting service and add RestBus hosting code

This code example is a modification of the ServiceStack self-hosting example

  • You need an installation of RabbitMQ to run the code sample.
  • Note that samba is the unique name of the service in this example.
	using RestBus.RabbitMQ;
	using RestBus.RabbitMQ.Subscription;
	using RestBus.ServiceStack;
	using ServiceStack.ServiceInterface;
	using ServiceStack.WebHost.Endpoints;
	using System;
	
	class Program
	{
	    public class Hello
	    {
	        public string Name { get; set; }
	    }
	
	    public class HelloResponse
	    {
	        public string Result { get; set; }
	    }
	
	    public class HelloService : Service
	    {
	        public object Any(Hello request)
	        {
	            return new HelloResponse { Result = "Hello, " + request.Name };
	        }
	    }
	
	    //Define the Web Services AppHost
	    public class AppHost : AppHostHttpListenerBase
	    {
	        public AppHost()
	            : base("HttpListener Self-Host", typeof(HelloService).Assembly) { }
	
	        public override void Configure(Funq.Container container)
	        {
	            Routes
	            .Add<Hello>("/hello")
	            .Add<Hello>("/hello/{Name}");
	        }
	    }
	
	    //Run it!
	    static void Main(string[] args)
	    {
	        var listeningOn = args.Length == 0 ? "http://*:1337/" : args[0];
	        var appHost = new AppHost();
	        appHost.Init();
	        //appHost.Start(listeningOn); //Uncommenting this line will enable this service to also receive requests via HTTP
	
	        Console.WriteLine("AppHost Created at {0}, listening on {1}",
	            DateTime.Now, listeningOn);
	
	        //*** Start RestBus subscriber/host **//
	
	        var amqpUrl = "amqp://localhost:5672"; //AMQP URI for RabbitMQ server
	        var serviceName = "samba"; //Uniquely identifies this service
	
	        var msgMapper = new BasicMessageMapper(amqpUrl, serviceName);
	        var subscriber = new RestBusSubscriber(msgMapper);
	        var host = new RestBusHost(subscriber);
	        host.Start();
	
	        //****//
	
	        Console.ReadKey();
	    }
	}

Make a request to the service

See Calling a Service Endpoint