Skip to content

Instantly share code, notes, and snippets.

@gregoryyoung
Created November 27, 2013 14:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gregoryyoung/7677015 to your computer and use it in GitHub Desktop.
Save gregoryyoung/7677015 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
{
public static void Initialize()
{
var dispatcher = new Dispatcher();
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
{
private readonly Dictionary<Type, Func<IMessage, object>> _dictionary = new Dictionary<Type, Func<IMessage, object>>();
public void Register<T>(Func<T, object> func) where T:IMessage
{
_dictionary.Add(typeof(T), x => func((T) x));
}
public object Dispatch(IMessage m)
{
Func<IMessage, object> 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 object 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