问题
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?
回答1:
Hy
This can be achieved with either a custom factory or the Ninject.Factory.Extension
which does all the magic behind the scenes. I'll show here the manual approach:
public interface IProcessFactory {
IProcess Create(int value);
}
public class ProcessFactory : IProcessFactory {
public IProcess Create(int value)
{
return this.kernel.Get<IProcess>(new Parameter("value", value, true));
}
}
somewhere in a module:
this.Bind<IProcess>().To<Process>();
this.Bind<IOption>().To<Option>()
.OnActivation((ctx, o) => o.SetValue((int)ctx.Parameters.Single(p => p.Name == "value").GetValue(ctx, ctx.Request.Target)));
I think there should be also an extension method somewhere in a ninject extension which allows to simplify the OnActivation
call.
来源:https://stackoverflow.com/questions/10778567/how-to-pass-parameters-to-a-transient-object-created-by-ninject