Ninject:将构造函数参数绑定到其他对象的属性

Ada*_*ger 14 c# ninject

我有一个IConfig对象,其中包含我的应用程序中使用的设置.目前,我将整个对象注入到需要它的每个对象的构造函数中,如下所示:

public interface IConfig 
{
    string Username { get; }
    string Password { get; }
    //... other settings
}

public class Foo : IFoo
{
    private readonly string username;
    private readonly string password;

    public Foo(IConfig config)
    {
        this.username = config.Username;
        this.password = config.Password;
    }
}
Run Code Online (Sandbox Code Playgroud)

缺点是IConfig包含大量设置,因为它是从整个配置文件中反序列化的,因此不必注入整个对象.我想要做的是将构造函数更改为Foo(string username, string password)只接收它需要的设置.这也使得创建Foo测试对象变得更加容易(不必IConfig仅仅为了创建而设置Foo).我想直接在我的绑定构造函数参数NinjectModule,如下所示:

public class MyModule : NinjectModule
{
    public override void Load()
    {
        Bind<IConfig>().To<JsonConfig>()
            .InSingletonScope();

        Bind<IFoo>().To<Foo>()
            .WithConstructorArgument("username", IConfig.Username)
            .WithConstructorArgument("password", IConfig.Password);
    }
}
Run Code Online (Sandbox Code Playgroud)

显然这段代码不起作用,但我怎么去做我想要的呢?

我最初的想法是使用NinjectModule.Kernel获取IKernel然后获取我的IConfig对象的实例并根据需要注入属性,但返回的对象NinjectModule.Kernel没有Get<T>()方法.

nem*_*esv 15

你走在正确的轨道上:

Kernel.Get<T>()方法是ResolutionExtensionsNinjectnamepsace中定义的扩展方法,因此添加using Ninject;它也可以在您的模块中使用.

但是,而不是Module.Kernel你应该使用IContext提供了第二超载WithConstructorArgument来获得Kernel:

Bind<IFoo>().To<Foo>()
    .WithConstructorArgument("username", 
                             context => context.Kernel.Get<IConfig>().Username)
    .WithConstructorArgument("password", 
                             context => context.Kernel.Get<IConfig>().Password);
Run Code Online (Sandbox Code Playgroud)