将构造函数参数添加到 Ninject 绑定

Gra*_*Roy 2 c# dependency-injection ninject ioc-container

我有一个 ASP.MVC 项目,其中使用 ninject 作为 IOC 容器。我已将绑定添加为基础结构文件夹中的单独类,如下所示:

public class NinjectControllerFactory : DefaultControllerFactory{

  private readonly IKernel _ninjectKernal;

  public NinjectControllerFactory()
  {
    _ninjectKernal = new StandardKernel();

    PSCCheckContext m = _ninjectKernal.Get<PSCCheckContext>(new IParameter[] 
        { new ConstructorArgument("appNamekey", "Name of Staff Application"), 
            new ConstructorArgument("serverLocationNameKey", "Location of Application Server") });

    AddBindings();
  }
Run Code Online (Sandbox Code Playgroud)

所以您可以看到我正在尝试在 PSCCheckContext 的构造函数中设置 web.config 中的两个参数。这是另一个处理数据库访问的 C# 应用程序。AddBindings() 类只是将接口类映射到您所期望的具体实现:

private void AddBindings()
{
  ...
  _ninjectKernal.Bind<IPSCCheckContext>().To<PSCCheckContext>();
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是 PSCCheckContext 类中有 2 个构造函数,其中第二个构造函数采用不同的参数:

public class PSCCheckContext : IPSCCheckContext
{
  public PSCCheckContext(string appNamekey, string serverLocationNameKey);
  public PSCCheckContext(string imgNamekey, string imgFlagKey, string serverLocationKeyName);
Run Code Online (Sandbox Code Playgroud)

当我尝试点击 Ninject 注入此绑定的控制器时,出现以下错误:

激活字符串时出错。没有可用的匹配绑定,并且该类型不可自绑定。

激活路径:
3) 将依赖字符串注入到 PSCCheckContext 类型的构造函数的参数 imgNamekey
2) 将依赖项 IPSCCheckContext 注入到 AccountController 类型的构造函数的参数 pscCheckContext
1) 请求 AccountController

建议:
1) 确保您已定义字符串的绑定。
2) 如果绑定是在模块中定义的,请确保该模块已加载到内核中。
3) 确保您没有意外创建多个内核。
4) 如果您使用构造函数参数,请确保参数名称与构造函数参数名称匹配。
5) 如果您使用自动模块加载,请确保搜索路径和过滤器正确。

即使我将绑定更改得更好(已阅读http://thebrainyprofessionals.com/2013/05/20/passing-constructor-parameters-in-ninject/)

IParameter appNamekey = new ConstructorArgument("appNamekey", "Name of Staff Application");
IParameter serverLocationNameKey = new ConstructorArgument("serverLocationNameKey", "Location of Application Server");
_ninjectKernal.Bind<IPSCCheckContext>().To<PSCCheckContext>()
  .WithConstructorArgument(appNamekey)
  .WithConstructorArgument(serverLocationNameKey);
Run Code Online (Sandbox Code Playgroud)

我仍然遇到同样的错误。我读过各种SO问题:

将值注入到注入的依赖项中

使用 Ninject 创建一个实例,并在构造函数中添加附加参数

构造函数字符串参数与 Ninject 的基于约定的绑定

但似乎没有人遇到我的问题。

我究竟做错了什么?

我无法删除附加构造函数,因为它位于不同的应用程序中,并且我认为它正在由不同的系统使用。

为了完整性,这是 AccountController 构造函数

public class AccountController : BaseController

  private readonly IPSCCheckContext _pscCheckContext;

  public AccountController(IPSCCheckContext pscCheckContext)
  {
    this._pscCheckContext = pscCheckContext;
Run Code Online (Sandbox Code Playgroud)

Hoo*_*ini 5

你也可以尝试这个:

kernel.Bind<IPSCCheckContext>().ToConstructor(ctorArg => new PSCCheckContext(
    "Name of Staff Application", 
    "Location of Application Server"));
Run Code Online (Sandbox Code Playgroud)

与 相比,我更喜欢这个WithConstructorArgument,因为如果您更改了 arg 名称,您的 DI 绑定将不会中断。