在使控制器IoC框架不可知的同时,如何将Ninject与ActionResults一起使用?

时间:2010-11-03 00:47:51

标签: asp.net-mvc-2 dependency-injection inversion-of-control ninject actionresult

我见过的几乎所有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将为null。但是,按照以下方式进行操作对我来说似乎并不合适:

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

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

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

2 个答案:

答案 0 :(得分:12)

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

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

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

答案 1 :(得分: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;
}
相关问题