Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NInject: how to pass parameters when Get<T>()?

Tags:

ninject

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

like image 302
Zach Avatar asked May 30 '12 02:05

Zach


2 Answers

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;
}
like image 81
Jerry Wang Avatar answered Sep 28 '22 05:09

Jerry Wang


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

like image 36
Zach Avatar answered Sep 28 '22 06:09

Zach