Created
August 21, 2013 19:40
-
-
Save mastoj/6299180 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel.Design; | |
using System.Linq; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace CQRSDemo | |
{ | |
class Program | |
{ | |
private static readonly CommandDispatcher Dispatcher = new CommandDispatcher(); | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("Welcome to this simple CQRS demo"); | |
string commandText = ""; | |
while (!string.IsNullOrEmpty((commandText = Console.ReadLine()))) | |
{ | |
var command = ParseCommand(commandText); | |
Dispatcher.HandleCommand(command); | |
} | |
} | |
private static ICommand ParseCommand(string commandText) | |
{ | |
return new CreateSkjema(commandText); | |
} | |
} | |
public class CommandDispatcher | |
{ | |
private Dictionary<Type, Action<object>> _commandHandlers = new Dictionary<Type, Action<object>>(); | |
public CommandDispatcher() | |
{ | |
var skjemaHandler = new SkjemaHandler(); | |
Register<CreateSkjema>(skjemaHandler.Handle); | |
} | |
private void Register<TCommand>(Action<TCommand> handle) where TCommand : class | |
{ | |
_commandHandlers.Add(typeof (TCommand), (y) => handle(y as TCommand)); | |
} | |
public void HandleCommand(ICommand command) | |
{ | |
var type = command.GetType(); | |
if (_commandHandlers.ContainsKey(type)) | |
{ | |
_commandHandlers[type](command); | |
} | |
else | |
{ | |
throw new MissingHandlerException(command); | |
} | |
} | |
} | |
public class MissingHandlerException : Exception | |
{ | |
public MissingHandlerException(ICommand command): base("Missing handler for command: " + command.GetType()) | |
{ | |
} | |
} | |
public interface ICommand | |
{ | |
} | |
public class CreateSkjema : ICommand | |
{ | |
public CreateSkjema(string commandText) | |
{ | |
Navn = commandText; | |
} | |
public string Navn { get; private set; } | |
} | |
public class SkjemaHandler : IHandle<CreateSkjema> | |
{ | |
public void Handle(CreateSkjema command) | |
{ | |
Console.WriteLine("Skjema created"); | |
} | |
} | |
public interface IConsume<TEvent> where TEvent : IEvent | |
{ | |
void Handle(TEvent command); | |
} | |
public interface IEvent | |
{ | |
} | |
public interface IHandle<TCommand> where TCommand : ICommand | |
{ | |
void Handle(TCommand command); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment