Skip to content

Instantly share code, notes, and snippets.

@gregoryyoung
Created November 27, 2013 15:07
Show Gist options
  • Save gregoryyoung/7677189 to your computer and use it in GitHub Desktop.
Save gregoryyoung/7677189 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace crap
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
public class PartialAppPlayground
{
private static Dispatcher _dispatcher;
public static void Initialize()
{
_dispatcher = new Dispatcher();
_dispatcher.Register<DoBar>(message => CommandHandlers.Bar(() => new SqlConnection(), message));
_dispatcher.Register<DoFoo>(message => CommandHandlers.Foo(new SqlConnection(), message));
}
public static void Main()
{
Initialize();
_dispatcher.Dispatch(new DoBar());
_dispatcher.Dispatch(new DoFoo());
}
}
public class Dispatcher
{
private readonly Dictionary<Type, Action<Command>> _dictionary = new Dictionary<Type, Action<Command>>();
public void Register<T>(Action<T> func) where T:Command
{
_dictionary.Add(typeof(T), x => func((T) x));
}
public void Dispatch(Command m)
{
Action<Command> handler;
if(!_dictionary.TryGetValue(m.GetType(), out handler))
{
throw new Exception("cannot map " + m.GetType());
}
handler(m);
}
}
public interface Command : Message { }
public interface Message { }
public class DoFoo : Command
{
public string Something { get; set; }
}
public class DoBar : Command
{
public string Something { get; set; }
}
public static class CommandHandlers
{
public static void Bar(Func<IDbConnection> connection, DoBar command)
{
Console.WriteLine("bar");
}
public static void Foo(IDbConnection connection, DoFoo command)
{
Console.WriteLine("foo");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment