首页 文章

在构造函数中传递Func <bool>参数导致Ninject问题

提问于
浏览
1

我正在创建一个使用interface as的工厂

public interface ICommandFactory
{
  ICommand CreateCommand(Action executeMethod);
  ICommand CreateCommand(Action executeMethod, Func<bool> canExecuteMethod);
}

public class DelegateCommand : DelegateCommand<object>
{
    public DelegateCommand(Action executeMethod)
        : base(o => executeMethod())
    {
    }

    public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)
        : base(o => executeMethod(), o => canExecuteMethod())
    {
    }
}

public class DelegateCommand<T> : ICommand
{
    public DelegateCommand(Action<T> executeMethod)
        : this(executeMethod, null)
    {
    }

    public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
    {

    }
}

我的Ninject绑定是使用完成的

_kernel.Bind(x => x.FromAssembliesMatching("xyz*")
                        .SelectAllClasses()                                
                        .BindAllInterfaces());

_kernel.Bind(x => x.FromAssembliesMatching("xyz*")
                        .SelectAllInterfaces()
                        .EndingWith("Factory")
                        .BindToFactory()
                        .Configure(c => c.InSingletonScope()));

当我在我的视图模型中调用时,它会导致激活异常,尽管我尝试使用命名绑定 .

public class MyViewModel
{
  public ICommand SaveCommand {get; private set;}

  public MyViewModel(ICommandFactory commandFactory)
  {
    SaveCommand = commandFactory.CreateCommand(Save, () => SelectedTask != null);
  }
}

在'o => canExecuteMethod()'行上的DelegateCommand构造函数中引起异常 . 另外,我不能在Ninject中使用构造函数param传递,因为我的canExecute逻辑在我的ViewModel中 . 接受任何解决方案或修复 .

1 回答

  • 0

    您的问题是由Ninject.Extensions.Factory为 Func<> 创建绑定引起的 .

    当您使用所述扩展时,配置ninject以便您可以将 Func<> 作为工厂注入 . Func<bool> 基本上就像绑定一样

    kernel.Bind<Func<bool>>().ToMethod(() => 
    {
        return (Func<bool>) = () => kernel.Get<bool>();
    }
    

    现在这与事实配对,即ninject将使用具有可以解析的最多参数的公共构造函数 . 这意味着,即使您使用 CreateCommand(Action executeMethod); ,ninject也将使用 public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod) 构造函数并注入"bool factory"作为 Func<bool> 参数 .

    解决方法

    Wrapping the Func in an interface

    有很多方法可以做到这一点,让我告诉你一个:

    public class Wrapper<T>
    {
        public T Wrapped { get; set; }
    }
    

    并使工厂适应:

    public interface ICommandFactory
    {
      ICommand CreateCommand(Action executeMethod, Wrapper<Func<bool>> canExecuteMethod);
    }
    

    和委托命令构造函数:

    public class DelegateCommand : ICommand
    {
        public DelegateCommand(Action<T> executeMethod, Wrapper<Func<bool>> canExecuteMethod)
        {
        }
    }
    

    Removing the factory extensions Func bindings

    Stop Ninject from binding Func<T, T, bool> automatically

相关问题