注意:在开始之前请注意这在ICommandHandler的定义被更改为包含多个通用约束之前完美地工作,只有一个约束它可以正常工作。
但是,我似乎没有将多个约束传递到选择器的“arguments”数组中。我错过了什么吗?
这称为:
var handler = _factory.GetHandlerForCommand<TCommand, TResult>(command);
工厂界面:
public interface ICommandHandlerFactory
{
ICommandHandler<TCommand, TResult> GetHandlerForCommand<TCommand, TResult>(ICommand command)
where TCommand : class, ICommand
where TResult : IDTOBase;
}
Selector类:
public class HandlerSelector : DefaultTypedFactoryComponentSelector
{
protected override Func<Castle.MicroKernel.IKernelInternal, Castle.MicroKernel.IReleasePolicy, object> BuildFactoryComponent(System.Reflection.MethodInfo method, string componentName, Type componentType, System.Collections.IDictionary additionalArguments)
{
return new HandlerResolver(componentName,
componentType,
additionalArguments,
FallbackToResolveByTypeIfNameNotFound,
GetType()).Resolve;
}
protected override string GetComponentName(System.Reflection.MethodInfo method, object[] arguments)
{
return null;
}
protected override Type GetComponentType(System.Reflection.MethodInfo method, object[] arguments)
{
var message = arguments[0];
var handlerType = typeof (ICommandHandler<,>).MakeGenericType(message.GetType());
return handlerType;
}
}
Windsor安装程序文件:
container
.Register(
Component
.For<HandlerSelector>()
.ImplementedBy<HandlerSelector>(),
AllTypes
.FromAssemblyContaining<ICommandHandlerFactory>()
.BasedOn(typeof(ICommandHandler<,>))
.WithService.Base()
.Configure(c => c.LifeStyle.Is(LifestyleType.PerWebRequest)),
Component
.For<ICommandHandlerFactory>()
.AsFactory(c => c.SelectedWith<HandlerSelector>()));
答案 0 :(得分:2)
通常情况下,以连贯的方式撰写问题通常会得到答案。
将选择器代码更改为:
var genericArgs = method.GetGenericArguments();
var handlerType = typeof(ICommandHandler<,>).MakeGenericType(genericArgs[0], genericArgs[1]);
return handlerType;
解决问题。