How to pass parameters to a transient object created by Ninject?

自闭症网瘾萝莉.ら 提交于 2019-12-24 15:31:51

问题


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

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