如何将参数传递给Ninject创建的瞬态对象? [英] How to pass parameters to a transient object created by Ninject?

查看:74
本文介绍了如何将参数传递给Ninject创建的瞬态对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NInject开发ASP.NET MVC 3项目来创建对象实例.它为每个动作构建一个对象图.在大多数情况下,它运作良好.但是,我有一个新要求,即必须将一些参数(来自请求)传递给对象图中的几个对象(瞬态). 我怎样才能做到这一点?这是一个示例:

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

如上面的代码所示,Process属性注入了由NInject创建的IProcess实例.幕后有一个复杂的对象图.我想将值"传递给对象图中的对象之一,该对象图是由IProcess实例使用的IOptions的瞬时实例. IOptions接口具有一个名为SetValue(int)的方法.

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).

我想做的是,当创建IOptions对象时,将调用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.

有什么主意吗?

推荐答案

Hy 这可以通过自定义工厂或Ninject.Factory.Extension来实现,它可以完成所有幕后工作.我将在此处显示手动方法:

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

模块中的某处:

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

我认为ninject扩展中的某处也应该有一个扩展方法,可以简化OnActivation调用.

I think there should be also an extension method somewhere in a ninject extension which allows to simplify the OnActivation call.

这篇关于如何将参数传递给Ninject创建的瞬态对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆