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

时间:2014-08-07 08:25:31

标签: ninject

我正在使用接口

创建工厂
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);
  }
}

异常是由DelegateCommand的构造函数引起的,&#39; o =&gt; canExecuteMethod()&#39;线。另外,我不能在Ninject中使用构造函数param传递,因为我的逻辑canExecute在我的ViewModel中。任何解决方案或修复都被接受。

1 个答案:

答案 0 :(得分: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)构造函数并注入&#34; bool工厂&#34;作为Func<bool>参数。

变通方法

在界面中包装Func

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

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)
    {
    }
}

删除工厂扩展程序Func绑定

请参阅Stop Ninject from binding Func<T, T, bool> automatically

相关问题