我如何使用Ninject与ActionResults同时使控制器的IoC框架无关? [英] How do I use Ninject with ActionResults while making the controller IoC-framework-agnostic?

查看:151
本文介绍了我如何使用Ninject与ActionResults同时使控制器的IoC框架无关?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几乎所有的Ninject例子我见过解释如何在ASP.NET MVC中,它会自动把依赖注入的控制器使用。我将如何使用Ninject手动虽然?比方说,我有一个自定义的ActionResult:

Nearly all of the Ninject examples I've seen explain how to use it with ASP.NET MVC, which will automatically inject dependencies into controllers. How would I use Ninject manually though? Let's say I have a custom 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的注入,而串行将是空的。但是,这样做以下方式似乎不太对我说:

As you can see, I'm instantiating the object myself, which sidesteps Ninject's injection, and Serializer will be null. However, doing it the following way doesn't seem quite right to me:

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

由于现在不仅是一个在控制器上Ninject的依赖,但我也有揭露Ninject内核静态类/单身,并确保依赖注入物体只能通过内核创建的。

Because now there's not only a dependency on Ninject in the controller, but I also have to expose the Ninject kernel in a static class/singleton and ensure that objects that rely on injection are only created via kernel.

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

Is there a way to somehow configure Ninject to inject the dependency without relying on exposing the kernel? I'd like to be able to use the new keyword if at all possible.

推荐答案

使用一个工厂,获得注入的内核:例如

Use a factory that gets the kernel injected: E.g.

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

注入这家工厂到控制器,并使用它来创建你的行动的结果。

Inject this factory into the controller and use it to create your action results.

这篇关于我如何使用Ninject与ActionResults同时使控制器的IoC框架无关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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