Skip to content

Instantly share code, notes, and snippets.

@alexeyzimarev
Forked from gregoryyoung/gist:7690486
Last active August 29, 2015 14:07
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 alexeyzimarev/dd5b4e9c2a993f7ff97b to your computer and use it in GitHub Desktop.
Save alexeyzimarev/dd5b4e9c2a993f7ff97b to your computer and use it in GitHub Desktop.
namespace crap
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
public class PartialAppPlayground
{
private static Dispatcher<Command, Nothing> _dispatcher;
public static void Initialize()
{
_dispatcher = new Dispatcher<Command, Nothing>();
_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<TMessage, TResult> where TResult:class
{
private readonly Dictionary<Type, Func<TMessage, TResult>> _dictionary = new Dictionary<Type, Func<TMessage, TResult>>();
public void Register<T>(Func<T, TResult> func) where T : TMessage
{
}
public void Register<T>(Action<T> action) where T : TMessage
{
Action<TMessage> casted = x => action((T) x);
_dictionary.Add(typeof(T), q => {
casted(q);
return Nothing.Value as TResult;
});
}
public TResult Dispatch(TMessage m)
{
Func<TMessage, TResult> handler;
if (!_dictionary.TryGetValue(m.GetType(), out handler))
{
throw new Exception("cannot map " + m.GetType());
}
return handler(m);
}
}
public class Nothing
{
private Nothing() { }
public static readonly Nothing Value = new Nothing();
public override string ToString()
{
return "Nothing";
}
}
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