Skip to content

Instantly share code, notes, and snippets.

@bryanhunter
Created February 7, 2012 16:42
Show Gist options
  • Save bryanhunter/1760607 to your computer and use it in GitHub Desktop.
Save bryanhunter/1760607 to your computer and use it in GitHub Desktop.
Commands sent to a CommandRouter get routed to the appropriate CommandHandler (using Castle.Windsor)
using System;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
namespace CollectionResolverForGenericInterface
{
internal class Program
{
private static void Main(string[] args)
{
var container = new WindsorContainer();
container.Register(Component.For<IWindsorContainer>().Instance(container));
container.Register(Component.For<ICommandRouter>().ImplementedBy<CommandRouter>().LifeStyle.Transient);
container.Register(AllTypes.FromThisAssembly()
.BasedOn(typeof (ICommandHandler<>))
.WithService.AllInterfaces()
.LifestyleTransient()
.AllowMultipleMatches());
var router = container.Resolve<ICommandRouter>();
router.Publish(new TurnLightOnCommand());
router.Publish(new PourMilkCommand());
router.Publish(new TurnLightOffCommand());
router.Publish(new Guid()); // Will be discarded
}
}
public interface ICommandRouter
{
void Publish<T>(T command);
}
public class CommandRouter : ICommandRouter
{
private readonly IWindsorContainer _container;
public CommandRouter(IWindsorContainer container)
{
_container = container;
}
public void Publish<T>(T command)
{
ICommandHandler<T>[] handlers = _container.ResolveAll<ICommandHandler<T>>();
foreach (var handler in handlers)
handler.Handle(command);
}
}
public interface ICommand
{
}
public interface ICommandHandler<in T>
{
void Handle(T command);
}
public class TurnLightOnCommand : ICommand
{
}
public class TurnLightOffCommand : ICommand
{
}
public class PourMilkCommand : ICommand
{
}
public class TurnLightOffCommandHandler : ICommandHandler<TurnLightOffCommand>
{
public void Handle(TurnLightOffCommand command)
{
Console.WriteLine("Turning Off Light");
}
}
public class TurnLightOnCommandHandler : ICommandHandler<TurnLightOnCommand>
{
public void Handle(TurnLightOnCommand command)
{
Console.WriteLine("Turning On Light");
}
}
public class PourMilkCommandHandler : ICommandHandler<PourMilkCommand>
{
public void Handle(PourMilkCommand command)
{
Console.WriteLine("Pouring Milk");
}
}
public class GreedyCommand : ICommandHandler<ICommand>
{
public void Handle(ICommand command)
{
Console.WriteLine("I like commands"); // Greedy command doesn't get called
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment