Dan*_* T. 3 dependency-injection ninject inversion-of-control actionresult asp.net-mvc-2
我见过的几乎所有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
}
Run Code Online (Sandbox Code Playgroud)
然后在我的控制器中,我正在使用这样JsonResult
的方法:
public ActionResult Get(int id)
{
var someObject = repo.GetObject(id);
return new JsonResult(someObject);
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我自己实例化了这个对象,它回避了Ninject的注入,并且Serializer
将为null.但是,按照以下方式执行此操作对我来说似乎并不合适:
public ActionResult Get(int id)
{
var someObject = repo.GetObject(id);
return IoC.Kernel.Get<JsonResult>(someObject);
}
Run Code Online (Sandbox Code Playgroud)
因为现在控制器中不仅存在对Ninject的依赖,而且还必须在静态类/单例中公开Ninject内核,并确保依赖注入的对象仅通过内核创建.
有没有办法以某种方式配置Ninject注入依赖,而不依赖于暴露内核?new
如果可能的话,我希望能够使用关键字.
Rem*_*oor 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;
}
}
Run Code Online (Sandbox Code Playgroud)
将此工厂注入控制器并使用它来创建操作结果.