Ninject: Bind Constructor Argument to Property of Other Object

可紊 提交于 2019-11-30 08:31:53

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

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.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!