使用反射向其处理程序注册命令

时间:2013-11-14 00:07:01

标签: c# .net design-patterns reflection

public interface ICommandService
{
    void Handle(Command command);
    void RegisterHandler<T>(Action<T> handler);
}
public class CampaignCommandHandler
{ 
  .
  .
   .
   public void Handle(RegisterCampaignCommand command)
    {
          //Some code here
     }
   .
   .
}

目前正在手动注册带有处理程序的命令。

commandService.RegisterHandler<RegisterCampaignCommand>(campaignCommandHandler.Handle);

我有很多命令,每个命令都在CampaignCommandHandler类中有一个句柄功能。

var handles = campaignCommandHandler.GetType().GetMethods().Where(x => x.Name == "Handle");

  foreach (var handle in handles)
   {
      var command = handle.GetParameters().FirstOrDefault(x => x.ParameterType.BaseType == typeof(Command));

        // This is something, I want to do, which is obviously not the right as is 
       commandService.RegisterHandler<command.GetType()>(GetActionfromMethodInfo(handle)); 

   }

我正在努力做到以上但不确定如何使用反射来做到这一点。 我想知道是否有人可以指导我。

感谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

var methods = campaignCommandHandler.GetType().GetMethods().Where(x => x.Name == "Handle");
foreach(var method in methods)
{
    var parameter = method.GetParameters().FirstOrDefault(x => typeof(Command).IsAssignableFrom(x.ParameterType));
    if(parameter == null)
    {
        continue;
    }
    var commandType    = parameter.ParameterType;
    var handler        = method.CreateDelegate(typeof(Action<>).MakeGenericType(commandType), campaignCommandHandler);
    var registerMethod = commandService.GetType().GetMethod("RegisterHandler").MakeGenericMethod(commandType);

    registerMethod.Invoke(commandService, new object[] { handler });
}
相关问题