Skip to content

Instantly share code, notes, and snippets.

@jmarnold
Created September 10, 2011 18:06
Show Gist options
  • Save jmarnold/1208582 to your computer and use it in GitHub Desktop.
Save jmarnold/1208582 to your computer and use it in GitHub Desktop.
Conventional Command Invocation
public class CommandInvocationSource : IActionSource
{
private readonly IContainer _container;
public CommandInvocationSource()
{
_container = ObjectFactory.Container;
}
public IEnumerable<ActionCall> FindActions(TypePool types)
{
return _container
.Model
.InstancesOf(typeof (ICommand<>))
.Select(r =>
{
var actionType = typeof (InvokeCommandAction<,>);
var entityType = r.ConcreteType
.FindInterfaceThatCloses(typeof (ICommand<>))
.GetGenericArguments()[0];
actionType = actionType.MakeGenericType(entityType, r.ConcreteType);
var method = actionType.GetMethod("Execute", BindingFlags.Public | BindingFlags.Instance);
return new ActionCall(actionType, method);
});
}
}
public class CommandInvocationUrlPolicy : IUrlPolicy
{
public static readonly string Command = "Command";
public bool Matches(ActionCall call, IConfigurationObserver log)
{
if(!call.IsCommandInvocationCall())
{
return false;
}
log.RecordCallStatus(call, "Matched on {0}".ToFormat(GetType().Name));
return true;
}
public IRouteDefinition Build(ActionCall call)
{
var route = call.ToRouteDefinition();
var handlerType = call.HandlerType;
var genericArgs = handlerType.GetGenericArguments();
var entityType = genericArgs[0];
var commandType = genericArgs[1];
route.Append(entityType.Name.ToLower().AsPlural());
var commandName = commandType
.Name
.Replace(Command, string.Empty)
.Replace(entityType.Name, string.Empty)
.ToLower();
route.Append(commandName); // e.g., CreateCaseCommand => cases/create (POST)
route.ConstrainToHttpMethods("POST");
return route;
}
}
public class InvokeCommandAction<TEntity, TCommand>
where TEntity : IAggregate
where TCommand : class, ICommand<TEntity>
{
private readonly ICommandInvoker _invoker;
public InvokeCommandAction(ICommandInvoker invoker)
{
_invoker = invoker;
}
public CommandResult<TEntity> Execute(TCommand command)
{
var result = new CommandResult<TEntity>
{
AggregateId = command.Id,
Success = true
};
try
{
_invoker.Invoke(command);
}
catch (Exception exc)
{
result.Success = false;
result.RegisterError(exc.Message);
}
return result;
}
}
@drusellers
Copy link

What does 'IsCommandInvocationCall' look like?

@jmarnold
Copy link
Author

Just checks to see if the ActionCall HandlerType property closes InvokeCommandAction<,>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment