Skip to content

Instantly share code, notes, and snippets.

@scottmcarthur
Created June 10, 2014 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottmcarthur/d77e494e1a5e09ad0d08 to your computer and use it in GitHub Desktop.
Save scottmcarthur/d77e494e1a5e09ad0d08 to your computer and use it in GitHub Desktop.
Shows using an EventHandler in a dependency within a ServiceStack service
using System;
using ServiceStack;
using Funq;
using System.Timers;
namespace RedisTest
{
class MainClass
{
public static void Main()
{
var appHost = new AppHost();
appHost.Init();
appHost.Start("http://*:9000/");
Console.ReadKey();
}
}
public class AppHost : AppHostHttpListenerBase
{
public AppHost() : base("Test", typeof(AppHost).Assembly) { }
public override void Configure(Container container)
{
var dashboard = new DashboardAdapter();
container.Register(dashboard);
}
}
// As simple DashboardAdapter that toggles between isConnected and triggers the event
public class DashboardAdapter
{
public event ConnectionHandler OnConnection;
public delegate void ConnectionHandler(object sender, ConnectionEventArgs e);
readonly Timer timer;
bool isConnected;
public DashboardAdapter()
{
Console.WriteLine("Created Dashboard Adapter");
timer = new Timer(10000);
timer.Elapsed += (sender, args) => {
isConnected = !isConnected;
Console.WriteLine("Dashboard IsConnected: {0}", isConnected);
OnConnection(this, new ConnectionEventArgs { IsConnected = isConnected });
};
timer.Start();
}
}
public class DashboardService : Service
{
readonly DashboardAdapter _dashboardAdapter;
bool _isConnected;
public DashboardService(DashboardAdapter dashboardAdapter)
{
_dashboardAdapter = dashboardAdapter;
_dashboardAdapter.OnConnection += OnConnection;
}
public object Get(DashboardRequest request)
{
// Wait until the connection is established
while(!_isConnected)
Console.Write(".");
Console.WriteLine("\nConnected!");
return new Dashboard { IsConnected = _isConnected };
}
void OnConnection(object sender, ConnectionEventArgs e)
{
Console.WriteLine("Service OnConnection IsConnected: {0}", e.IsConnected);
_isConnected = e.IsConnected;
}
}
[Route("/dashboard","GET")]
public class DashboardRequest
{
}
public class Dashboard
{
public bool IsConnected { get; set; }
}
public class ConnectionEventArgs
{
public bool IsConnected { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment