Created
November 27, 2013 14:55
-
-
Save gregoryyoung/7677015 to your computer and use it in GitHub Desktop.
This file contains 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
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