-
Notifications
You must be signed in to change notification settings - Fork 10
ITypedHandlerFactory Example
hyperletter edited this page Sep 10, 2012
·
1 revision
There is a ITypedHandlerFactory built into Hyperletter, but this is really basic. All it does is to find the type and create it through the activator. If you want to use a more sophisticated approach with for example dependency injection the following pattern can be used.
The following handler tries to inject the message into the constructor if possible, however the message will still be passed into the Execute-method of the resolved Handler.
internal class AutofacHandlerFactory : ITypedHandlerFactory {
private readonly IComponentContext _container;
public AutofacHandlerFactory(IComponentContext container) {
_container = container;
}
public ITypedHandler<TMessage> CreateHandler<THandler, TMessage>(TMessage message) {
var messageType = message.GetType();
return (ITypedHandler<TMessage>)_container.Resolve<THandler>(new ResolvedParameter((info, context) => IsAssignableToMessageType(info, messageType), (info, context) => message));
}
private bool IsAssignableToMessageType(ParameterInfo parameterInfo, Type messageType) {
return parameterInfo.ParameterType.IsAssignableFrom(messageType);
}
}