Skip to content

Instantly share code, notes, and snippets.

@cairey
Created July 20, 2012 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cairey/3151265 to your computer and use it in GitHub Desktop.
Save cairey/3151265 to your computer and use it in GitHub Desktop.
Command pattern using MEF
[Export(typeof(ICommandHandlerFactory))]
public class CommandHandlerFactory : ICommandHandlerFactory
{
private readonly IEnumerable<ICommandHandler> _commandHandlers;
[ImportingConstructor]
public CommandHandlerFactory([ImportMany]IEnumerable<ICommandHandler> commandHandlers)
{
_commandHandlers = commandHandlers;
}
public CommandHandlerWrapper<TCommand> Get<TCommand>(TCommand command)
{
foreach(var commandHandler in _commandHandlers.OfType<ICommandHandler<TCommand>>())
{
return new CommandHandlerWrapper<TCommand>(commandHandler, command);
}
throw new Exception(string.Format("Command handler not found for command: {0}", command));
}
}
public class CommandHandlerWrapper<TCommand>
{
public CommandHandlerWrapper(ICommandHandler<TCommand> commandHandler, TCommand command)
{
CommandHandler = commandHandler;
Command = command;
}
public void Execute()
{
CommandHandler.Execute(Command);
}
public ICommandHandler<TCommand> CommandHandler { get; private set; }
public TCommand Command { get; private set; }
}
public interface ICommandHandler
{
}
public interface ICommandHandler<in TCommand> : ICommandHandler
{
void Execute(TCommand command);
}
public interface ICommandHandlerFactory
{
CommandHandlerWrapper<TCommand> Get<TCommand>(TCommand command);
}
[Export(typeof(ICommandHandler))]
public class UnfitForDischargeStatusHandler : ICommandHandler<UnfitForDischargeStatusCommand>
{
[ImportingConstructor]
public UnfitForDischargeStatusHandler()
{
}
public void Execute(UnfitForDischargeStatusCommand command)
{
}
}
_commandHandlerFactory.Get(new UnfitForDischargeStatusCommand(patientId)).Execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment