带有Ninject的多个参数的构造方法

Mar*_*iar 14 c# ninject ioc-container

我想使用Ninject作为IoC容器,但无法理解如何在构造函数中创建一个具有多个参数的类的实例.基本上我有一个用于PCL库中的身份验证的服务接口,以及它在WP8项目中的实现,该项目在构造函数中接收cosumer密钥,secret和baseAddress:

//On PCL project
public interface IAuthorizationService {
 bool Authenticate();
}

//On WP8 Project
pubilc class MyAuthenticator : IAuthorizationService {
 public MyAuthenticator(string consumerKey, string consumerSecret, string baseAddress) { ... }
 public bool Authenticate() { ... }
}
Run Code Online (Sandbox Code Playgroud)

现在我需要配置Ninject模块,这样我就可以获得IAuthorizationService的实例.如果我的班级没有构造函数,我会这样做:

internal class Module : NinjectModule {
 public override void Load() {
  this.Bind<IAuthorizationService>().To<MyAuthenticator>();
 }
}
Run Code Online (Sandbox Code Playgroud)

如果它有构造函数的固定值,我会这样做:

internal class Module : NinjectModule {
 public override void Load() {
  this.Bind<IAuthorizationService>().To<MyAuthenticator>().WithConstructorArgument( */* fixed argument here*/* );
 }
}
Run Code Online (Sandbox Code Playgroud)

并获得一个实例 Module.Get<IAuthorizationService>()

但是如果构造函数参数在编译时无法解析呢?如何通过参数?绑定代码应该如何?

编辑了这个问题.

Bat*_*nit 11

这很容易.无论有多少构造函数参数,绑定都保持不变:

Bind<IAuthorizationService>().To<MyAuthenticator>();
Run Code Online (Sandbox Code Playgroud)

假设MyAuthenticator有一个带有一个类型参数的构造函数IFoo.你所要做的就是告诉ninject如何解决/创建一个IFoo.再次,非常简单:

Bind<IFoo>().To<Foo>();
Run Code Online (Sandbox Code Playgroud)

您不需要WithConstructorArgument,除非您想要覆盖ninject的默认行为.假设MyAuthenticator有一个类型的参数IFoo加上string seed你想要专门配置的另一个参数.你所需要的只是:

Bind<IFoo>().To<Foo>();
Bind<IAuthorizationService>().To<MyAuthenticator>()
    .WithConstructorArgument("seed", "initialSeedValue");
Run Code Online (Sandbox Code Playgroud)

无需指定IFoo参数的值!

  • 这就是问题所在,我的构造函数有字符串参数,但我不知道它们在绑定时间的值。 (2认同)