[英]Resolve dependencies when calling constructor using DI with ASP.NET 5
The web seems flooded with examples on how to use DI with ASP.NET 5 but not one of the examples shows how to call a constructor and resolve dependencies. Web上似乎充满了有关如何在ASP.NET 5中使用DI的示例,但是没有一个示例显示如何调用构造函数和解决依赖关系。
The following is just one of many cases: http://social.technet.microsoft.com/wiki/contents/articles/28875.dependency-injection-in-asp-net-vnext.aspx 以下只是许多情况之一: http : //social.technet.microsoft.com/wiki/contents/articles/28875.dependency-injection-in-asp-net-vnext.aspx
But what happens if I want to do the following: 但是,如果我要执行以下操作会发生什么:
var todoRepository = app.ApplicationServices.GetRequiredService<ITodoRepository>();
ToDoController controller = new TodoController(todoRepository);
Presumably this can be shorted to something like... 大概这可以简化为...
.Get<TodoController>()
Like you can in Ninject. 就像您可以在Ninject中一样。
Can someone explain how this can be done? 有人可以解释如何做到吗?
First, you'll want to make sure the class you want to construct is registered with the DI container. 首先,您需要确保要构造的类已在DI容器中注册。 (Given your example of a controller, it probably already is thanks to the MVC framework.)
(考虑到您的控制器示例,它可能已经归功于MVC框架。)
There's several ways to do this, the most basic of which is registering a Transient. 有几种方法可以执行此操作,其中最基本的方法是注册一个Transient。 Note this needs to be done in the
ConfigureServices
stage of your Startup
class. 请注意,这需要在
Startup
类的ConfigureServices
阶段中完成。
services.AddTransient<ToDoController>();
Once you have it registered, you can resolve it just like you would any other service: 注册后,就可以像解决其他任何服务一样解决该问题:
app.ApplicationServices.GetRequiredService<ToDoController>();
For more information, I'd recommend Victor Hurdugaci's blog on Dependency Injection in ASP.NET vNext . 有关更多信息,我建议Victor Hurdugaci的博客中ASP.NET vNext中的依赖注入 。 It was written for alpha, but it looks like it's still accurate.
它是为Alpha编写的,但看起来仍然准确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.