30

I'm using the attached image to explain what I meant.

  • I have a few classes managed by NInject. Some of them have a few singleton instances, and others are in transient scope. In the image, blue rectangles are singltons, red are transient. The Processor depends on other classes or instances.

  • I want to get the instance of Processor each time by using kernel.Get. However, each time I want to use different values for the objects used by the Processor. See Action1 and Action2 in the image. The code is not real but just for explanation here.

Is there any existing way can meet my needs?Pass parameters when Get

Zach
  • 5,715
  • 12
  • 47
  • 62

2 Answers2

42

You should be able to pass constructor arguments given that your Processor takes those dependencies as arguments in the constructor.

var foo = new Ninject.Parameters.ConstructorArgument("foo", new Foo());
var bar = new Ninject.Parameters.ConstructorArgument("bar", new Bar());
var processor = kernel.Get<IProcessor>(foo, bar);

public Processor (Foo foo, Bar bar){
    this.foo = foo;
    this.bar = bar;
}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Jerry Wang
  • 588
  • 5
  • 6
  • 1
    Thank you for your reply. However, I believe you misunderstood my question. It is not about changing bindings in the Binding phase, but about passing parameters in the Resolving phase. What I meant was when I try to get an instance of IProcessor, how to pass the values to the processor's dependencies: the instances of Foo and Bar. The object graphs in the two Actions are same, but the properties of each instance will have different values. – Zach May 31 '12 at 01:38
  • 1
    @Zach Sorry I did misunderstand your question. I edited my initial answer. – Jerry Wang Jun 22 '12 at 14:14
  • I dislike loosing the type safety compile time safety net so much. Feels like falling back to a language like Javascript where every magic is possible. DI and constructor arguments (other than registered interfaces) feel like a `don't` to me this way. – Mike de Klerk Apr 24 '18 at 19:31
  • Just an added note for those who are dense like me - the string value in `ConstructorArgument()` must match the variable name in the target method, **not** the variable name that is assigned the result of `ConstructorArgument()`. Hopefully this will save people some time in the future. – Conrad May 28 '19 at 21:43
1

Use the OnActivation() function can hook the event when a dependency is activated.

Zach
  • 5,715
  • 12
  • 47
  • 62