Created
November 28, 2013 11:31
-
-
Save gregoryyoung/7690486 to your computer and use it in GitHub Desktop.
updated to support actions to funcs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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