I’m developing an ASP.NET MVC 3 project using NInject to create object instances. It builds an object graph for each Action. It works well in most cases. However, I have a new requirement that I must pass some parameters (from request) to a few objects (which are transient) in the object graph.
How can I do that? Here is an example:
class MyController : Controller
{
[Inject]
public IProcess Process {get;set;}
public ActionResult MyAction(int value)
{
// how to pass the 'value' to an object (IOptions) created by NInject
this.Process.Run();
}
}
As shown in the code above, the Process property is injected with an instance of IProcess created by NInject. There is a complex object graph behind the scene. And I want to pass the ‘value’ to one of the objects in the object graph which is an transient instance of IOptions used by the IProcess instance. The IOptions interface has a method named SetValue(int).
The thing I want to do is, when the IOptions object is created, it’s SetValue(int) will be called. Of course, it should be thread-safe.
Any idea?
Hy
This can be achieved with either a custom factory or the
Ninject.Factory.Extensionwhich does all the magic behind the scenes. I’ll show here the manual approach:somewhere in a module:
I think there should be also an extension method somewhere in a ninject extension which allows to simplify the
OnActivationcall.