Skip to content

Instantly share code, notes, and snippets.

@matjanos
Last active February 13, 2020 11:10
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 matjanos/86b8c54e73419ba19aa70682bb2a8fd9 to your computer and use it in GitHub Desktop.
Save matjanos/86b8c54e73419ba19aa70682bb2a8fd9 to your computer and use it in GitHub Desktop.
public interface ICommandHandler<T> where T : ICommand
{
Task HandleAsync (T command);
}
////////////////////////////////////////////////////
class CommandDispatcher : ICommandDispatcher
{
private readonly IComponentContext _context;
public CommandDispatcher (IComponentContext componentContext)
{
_context = componentContext;
}
public async Task DispatchAsync<T> (T command) where T : ICommand
{
if (command == null)
{
throw new ArgumentException ($"Command {typeof(T).Name} cannot be empty");
}
var handler = _context.Resolve<ICommandHandler<T>>();
await handler.HandleAsync(command);
}
}
//////////////////////////////////////
public class CommandModule : Module
{
protected override void Load (ContainerBuilder builder)
{
var assembly = typeof (CommandModule).Assembly;
builder
.RegisterAssemblyTypes (assembly)
.AsClosedTypesOf (typeof (ICommandHandler<>))
.InstancePerLifetimeScope ();
builder
.RegisterType<CommandDispatcher> ()
.AsImplementedInterfaces ()
.InstancePerLifetimeScope ();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment