Skip to content

Instantly share code, notes, and snippets.

@gregoryyoung
Created November 27, 2013 15:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregoryyoung/7677410 to your computer and use it in GitHub Desktop.
Save gregoryyoung/7677410 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<IHandlerResult> _dispatcher;
public static void Main()
{
Initialize();
Console.WriteLine(_dispatcher.Dispatch(new UsersByLastNameQuery()));
}
public static void Initialize()
{
_dispatcher = new Dispatcher<IHandlerResult>();
Func<IDbConnection> createTestConnection = () => new SqlConnection();
_dispatcher.Register<UsersByLastNameQuery>(message => UsersByLastNameQueryHandler.Handle(message, createTestConnection));
//note this is using an object return you can change it to use TReturn as well
//in much the same way that the first argument works.
}
}
public class Dispatcher<TResult>
{
private readonly Dictionary<Type, Func<IMessage, TResult>> _dictionary = new Dictionary<Type, Func<IMessage, TResult>>();
public void Register<T>(Func<T, TResult> func) where T : IMessage
{
_dictionary.Add(typeof(T), x => func((T)x));
}
public TResult Dispatch(IMessage m)
{
Func<IMessage, TResult> handler;
if (!_dictionary.TryGetValue(m.GetType(), out handler))
{
throw new Exception("cannot map " + m.GetType());
}
return handler(m);
}
}
public class UsersByLastNameQuery : IMessage
{
public string LastName { get; set; }
}
public class UsersByLastNameQueryHandler
{
public static UsersByLastNameQueryResult Handle(UsersByLastNameQuery query, Func<IDbConnection> createConnection)
{
using (var connection = createConnection())
{
//SQL
return new UsersByLastNameQueryResult();
}
}
}
public class UsersByLastNameQueryResult : IHandlerResult
{
}
public interface IMessage
{
}
public interface IHandlerResult
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment