Constructor with multiple arguments with Ninject

后端 未结 2 1010
梦谈多话
梦谈多话 2021-02-05 13:23

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

相关标签:
2条回答
  • 2021-02-05 14:11

    It's very easy. No matter how many constructor arguments, the binding stays the same:

    Bind<IAuthorizationService>().To<MyAuthenticator>();
    

    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>();
    

    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");
    

    no need to specify the value of the IFoo parameter!

    0 讨论(0)
  • 2021-02-05 14:17

    Ninject can inject more than one constructor arguments like:

     Bind<IMyClass>().To<MyClass>().InSingletonScope()
                    .WithConstructorArgument("customerName", "Daenerys Targeryan")
                    .WithConstructorArgument("customerAddress", "King's Landing");
    

    It does not change how the binding works.

    0 讨论(0)
提交回复
热议问题