Ninject: Bind Constructor Argument to Property of Other Object

前端 未结 2 1506
不思量自难忘°
不思量自难忘° 2020-12-31 07:11

I have an IConfig object that contains settings used throughout my application. At the moment, I inject the entire object into the constructor of each object th

2条回答
  •  迷失自我
    2020-12-31 07:18

    You are on the right track:

    The Kernel.Get() method is an extension method defined on the ResolutionExtensions in the Ninject namepsace so with adding the using Ninject; it is available in your module as well.

    But instead of the Module.Kernel you should use the IContext provided in the second overload of WithConstructorArgument to get the Kernel:

    Bind().To()
        .WithConstructorArgument("username", 
                                 context => context.Kernel.Get().Username)
        .WithConstructorArgument("password", 
                                 context => context.Kernel.Get().Password);
    

提交回复
热议问题