Skip to content

Instantly share code, notes, and snippets.

@davidwhitney
Created April 5, 2011 14:58
Show Gist options
  • Save davidwhitney/903766 to your computer and use it in GitHub Desktop.
Save davidwhitney/903766 to your computer and use it in GitHub Desktop.
Type registry example for command processing
class Program
{
private static TypeRegistry _registry;
static void Main(string[] args)
{
_registry = new TypeRegistry();
_registry.RegisterHandlerFor<MyRequest, MyRequestProcessor>();
SomeActionMethod(new MyRequest {Id = 1000});
}
public static void SomeActionMethod(MyRequest request)
{
var processor = _registry.ProcessorFor(request);
processor.Execute();
}
}
public class ProcessMyRequestCommand
{
}
public class MyRequest
{
public int Id { get; set; }
}
public class MyRequestProcessor: RequestProcessorBase<MyRequest>
{
public override void ProcessRequest()
{
Console.WriteLine(CommandParameters.Id);
}
}
public abstract class RequestProcessorBase<TTheRequestIProcess>
{
public TTheRequestIProcess CommandParameters { get; set; }
public abstract void ProcessRequest();
public void Execute()
{
ProcessRequest();
}
}
public class TypeRegistry
{
private readonly Dictionary<Type, Type> _registry;
public TypeRegistry()
{
_registry = new Dictionary<Type, Type>();
}
public void RegisterHandlerFor<TRequestType, TRequestProcessor>()
{
_registry.Add(typeof(TRequestType), typeof(TRequestProcessor));
}
public RequestProcessorBase<TRequestType> ProcessorFor<TRequestType>(TRequestType request)
{
var processorType = _registry[typeof(TRequestType)];
var processor = (RequestProcessorBase<TRequestType>)Activator.CreateInstance(processorType);
processor.CommandParameters = request;
return processor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment