Ninject: Bind Constructor Argument to Property of Other Object

前端 未结 2 1507
不思量自难忘°
不思量自难忘° 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<T>() 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<IFoo>().To<Foo>()
        .WithConstructorArgument("username", 
                                 context => context.Kernel.Get<IConfig>().Username)
        .WithConstructorArgument("password", 
                                 context => context.Kernel.Get<IConfig>().Password);
    
    0 讨论(0)
  • 2020-12-31 07:29

    This could be a good candiate for the Interface segregation principle.

    In this case, define another interface such as an ICredentialConfig containing just the Username and Password properties, then make IConfig implement this interface.

    public Interface ICredentialConfig
    {
       string Username { get; }
       string Password { get; }
    }
    
    public Interface IConfig : ICredentialConfig
    {
       //... other settings
    }
    

    Now make Foo dependant on ICredentialConfig instead of IConfig. You can then:

    1. Inject your JsonConfig using Ninject, instead of having hardcoded parameter names.
    2. Implement/Mock an ICredentialConfig for instantiating Foo in tests, instead of having to implement the full IConfig interface.
    0 讨论(0)
提交回复
热议问题