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

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

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?

回答1:

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


回答2:

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



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