Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.