Dependency Injection with constructor parameters that aren't interfaces

后端 未结 2 1150
無奈伤痛
無奈伤痛 2021-02-03 13:16

I\'m still a newbie at DI, and I am trying to understand if I am thinking of things the wrong way. I am working on a toy problem when I want to represent a Die object that has

2条回答
  •  故里飘歌
    2021-02-03 13:18

    You could use ConstructorArgument together with Kernel.Get in this particular situation. Here is full sample.

    Module configuration

    public class ExampleKernel : NinjectModule
    {
        public override void Load()
        {
            Bind()
                .To();
    
            Bind()
                .ToSelf()
                .WithConstructorArgument("numSides", 6);
                               //  default value for numSides
        }
    }
    

    Resolving in code

    var d6 = kernel.Get(); // default numSides value
    var d20 = kernel.Get(new ConstructorArgument("numSides", 20)); // custom numSides
    
    Assert.That(d6.NumSides == 6);
    Assert.That(d20.NumSides == 20);
    

提交回复
热议问题