3

我见过的几乎所有 Ninject 示例都解释了如何将它与 ASP.NET MVC 一起使用,它会自动将依赖项注入控制器。我将如何手动使用 Ninject?假设我有一个自定义 ActionResult:

public class JsonResult : ActionResult
{
    [Inject] public ISerializer Serializer { get; set; }

    public JsonResult(object objectToSerialize)
    {
        // do something here
    }

    // more code that uses Serializer
}

然后在我的控制器中,我使用JsonResult这样的方法:

public ActionResult Get(int id)
{
    var someObject = repo.GetObject(id);
    return new JsonResult(someObject);
}

如您所见,我自己实例化了该对象,这回避了 Ninject 的注入,并且Serializer将为空。但是,按照以下方式进行操作对我来说似乎不太正确:

public ActionResult Get(int id)
{
    var someObject = repo.GetObject(id);
    return IoC.Kernel.Get<JsonResult>(someObject);
}

因为现在不仅在控制器中存在对 Ninject 的依赖,而且我还必须在静态类/单例中公开 Ninject 内核,并确保依赖注入的对象仅通过内核创建。

有没有办法以某种方式配置 Ninject 以注入依赖项而不依赖于暴露内核?如果可能的话,我希望能够使用new关键字。

4

2 回答 2

11

使用注入内核的工厂:例如

public class ResultFactory : IResultFactory
{
    public ResultFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public JsonResult CreateJsonResult(object obj)
    {
        var result = this.kernel.Get<JsonResult>();
        result.ObjectToSerialize = obj;
        return result;
    }
}

将此工厂注入控制器并使用它来创建您的操作结果。

于 2010-11-03T12:34:28.757 回答
0

我认为你应该把你的JsonResult里面翻出来:

public class JsonResult : ActionResult
{
    public ISerializer Serializer { get; private set; }

    public object ObjectToSerialize { get; set; }

    public JsonResult(ISerializer serializer)
    {
        this.Serializer = serializer;
    }

    // more code that uses Serializer
}

这样,您可以JsonResult像这样使用容器检索 :

public ActionResult Get(int id)
{
    var result = IoC.Kernel.Get<JsonResult>();

    result.ObjectToSerialize = repo.GetObject(id);

    return result;
}

更改签名JsonResult也使 Ninject 能够自动创建实例。因此,您可以让 Ninject 自动将其作为依赖项注入到您的控制器中:

public MyController(JsonResult result)
{
    this.result = result;
}

public ActionResult Get(int id)
{
    this.result.ObjectToSerialize = repo.GetObject(id);

    return this.result;
}
于 2010-11-03T07:17:26.477 回答