构造与Ninject多个参数 [英] Constructor with multiple arguments with Ninject
问题描述
我特林使用 Ninject 作为IoC容器,但不能了解如何创建有超过一类的一个实例1参数构造函数。基本上我有一个PCL库中用于身份验证的服务接口和其在该构造函数接收cosumer键,秘密和baseAddress一个WP8项目实施:
I am tring to use Ninject as a IoC container but could not understand how to create an instance of a class that has more than 1 parameter in the constructor. Basically I have a service interface for authentication in a PCL library and its implementation in a WP8 project that receives in the constructor the cosumer key, secret and 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() { ... }
}
现在我需要配置 Ninject 模块,这样我就可以得到IAuthorizationService的一个实例。
。如果我的班有没有构造函数,我会做:
Now I need to configure Ninject module so I can get an instance of IAuthorizationService. If my class had no constructors I would do:
internal class Module : NinjectModule {
public override void Load() {
this.Bind<IAuthorizationService>().To<MyAuthenticator>();
}
}
如果它的构造固定值,我会做
If it had fixed values for the constructor I would do:
internal class Module : NinjectModule {
public override void Load() {
this.Bind<IAuthorizationService>().To<MyAuthenticator>().WithConstructorArgument( */* fixed argument here*/* );
}
}
和获得一个实例 Module.Get< IAuthorizationService>()
但是,如果构造函数的参数不能在编译时解决?如何通过paramenters?绑定代码应该如何?
的编辑,以claryfy的问题。的
推荐答案
这很容易。不管有多少构造函数的参数,结合保持不变。
It's very easy. No matter how many constructor arguments, the binding stays the same:
Bind<IAuthorizationService>().To<MyAuthenticator>();
比方说, MyAuthenticator
有一个构造一个类型参数的IFoo
。
你所要做的就是告诉ninject它如何解决/创建一个的IFoo
。再次,很简单:
Let's say MyAuthenticator
had a constructor with one parameter of type IFoo
.
All you got to do is tell ninject how it can resolve/create an IFoo
. Again, very simple:
Bind<IFoo>().To<Foo>();
您不需要 WithConstructorArgument
如初, 除的情况下的要覆盖ninject的默认行为。比方说, MyAuthenticator
有类型的参数的IFoo
加上另一个参数字符串种子$ C要专门配置$ C>。所有你需要的是:
You don't need WithConstructorArgument
ever, except in case you want to override the default behavior of ninject. Let's say MyAuthenticator
has a parameter of type IFoo
plus another parameter string seed
which you want to configure specifically. All you'd need is:
Bind<IFoo>().To<Foo>();
Bind<IAuthorizationService>().To<MyAuthenticator>()
.WithConstructorArgument("seed", "initialSeedValue");
无需指定的值的IFoo
参数!
这篇关于构造与Ninject多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!