Created
April 5, 2011 14:58
-
-
Save davidwhitney/903766 to your computer and use it in GitHub Desktop.
Type registry example for command processing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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