Skip to content

Instantly share code, notes, and snippets.

@iamkoch
Last active August 29, 2015 14:21
Show Gist options
  • Save iamkoch/2e3c41fd09c3c9b14c61 to your computer and use it in GitHub Desktop.
Save iamkoch/2e3c41fd09c3c9b14c61 to your computer and use it in GitHub Desktop.
QueryProcessor without concrete implementation
public class QueryProcessorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component.For(typeof(IQueryProcessor))
.AsFactory(c => c.SelectedWith(new QueryProcessorFactorySelector()))
.LifestyleTransient());
}
}
public class QueryProcessorFactorySelector : DefaultTypedFactoryComponentSelector
{
protected override Func<IKernelInternal, IReleasePolicy, object> BuildFactoryComponent(MethodInfo method, string componentName, Type componentType, IDictionary additionalArguments)
{
return
new QueryProcessorHandlerResolver(
componentName,
componentType,
additionalArguments,
FallbackToResolveByTypeIfNameNotFound,
GetType()).Resolve;
}
protected override Type GetComponentType(MethodInfo method, object[] arguments)
{
var isQueryType =
new Func<Type, bool>(t =>
t.GetInterfaces().Where(i => i.IsGenericType).Any(i => i.GetGenericTypeDefinition() == typeof(IQuery<>)));
if (method.Name == "Process" && arguments.Length == 1 && isQueryType(arguments[0].GetType()))
{
var handlerType =
typeof(IQueryHandler<,>).MakeGenericType(arguments[0].GetType(), method.GetGenericArguments()[0]);
return handlerType;
}
if (method.Name == "ProcessAsync" && arguments.Length == 1
&& isQueryType(arguments[0].GetType()))
{
var handlerType =
typeof(IQueryHandlerAsync<,>).MakeGenericType(arguments[0].GetType(), method.GetGenericArguments()[0]);
return handlerType;
}
throw new ArgumentException("Invalid method called on Query processor. To add a new one you must update " + GetType().FullName);
}
}
public class QueryProcessorHandlerResolver : TypedFactoryComponentResolver
{
public QueryProcessorHandlerResolver(string componentName, Type componentType, IDictionary additionalArguments, bool fallbackToResolveByTypeIfNameNotFound, Type actualSelectorType)
: base(componentName, componentType, additionalArguments, fallbackToResolveByTypeIfNameNotFound, actualSelectorType)
{
}
public override object Resolve(IKernelInternal kernel, IReleasePolicy scope)
{
dynamic handler = kernel.Resolve(componentType, additionalArguments, scope);
var enumerator = additionalArguments.Values.GetEnumerator();
enumerator.MoveNext();
return handler.Handle((dynamic)enumerator.Current);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment