gpt4 book ai didi

asp.net-mvc-2 - 如何将 Ninject 与 ActionResults 结合使用,同时使 Controller 与 IoC 框架无关?

转载 作者:行者123 更新时间:2023-12-02 13:16:51 25 4
gpt4 key购买 nike

我见过的几乎所有 Ninject 示例都解释了如何将其与 ASP.NET MVC 一起使用,它将自动将依赖项注入(inject)到 Controller 中。我该如何手动使用 Ninject 呢?假设我有一个自定义 ActionResult:

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

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

// more code that uses Serializer
}

然后在我的 Controller 中,我在如下方法中使用 JsonResult:

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

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

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

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

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

最佳答案

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

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) Controller 并使用它来创建您的操作结果。

关于asp.net-mvc-2 - 如何将 Ninject 与 ActionResults 结合使用,同时使 Controller 与 IoC 框架无关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4083352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com