Ninject: Bind Constructor Argument to Property of Other Object

前端 未结 2 1518
不思量自难忘°
不思量自难忘° 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: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.

提交回复
热议问题