[英]How to pass another class instance to a controller constructor
I am very new to the controller model concept.我对 controller model 概念非常陌生。 I am not understanding how and where to call the constructor of HomeController and how to pass student class instance?我不明白如何以及在哪里调用 HomeController 的构造函数以及如何传递学生 class 实例?
private IStudent _student;
public HomeController(IStudent student)
{
_student= student;
}
public interface IStudent
{
// Some method
}
Maybe, the functionality of services.AddTransient(IStudent,Student<>) I want to understand.也许,我想了解 services.AddTransient(IStudent,Student<>) 的功能。
You do not call the constructor of a Controller yourself in your code.您不要在代码中自己调用 Controller 的构造函数。 This is what the ASP.NET Framework does whenever it needs an instance of the controller to perform an action that is defined in that controller.这就是 ASP.NET 框架在需要 controller 的实例来执行在 controller 中定义的操作时所做的事情。
Your HomeController is part of an ASP.NET application running on a (web) server.您的 HomeController 是在(Web)服务器上运行的 ASP.NET 应用程序的一部分。 A user can execute a function of this application by calling a specific URL.用户可以通过调用特定的 URL 来执行此应用程序的 function。
For example, if the HomeController contains an Action method like this:例如,如果 HomeController 包含这样的 Action 方法:
public ActionResult Info()
{
// do something, then return result
...
return View();
}
this method would be executed whenever an URL similar to http://<server>/Home/Info
is called.每当调用类似于http://<server>/Home/Info
的 URL 时,都会执行此方法。
If you need information from a student instance inside the controller, you can pass it via dependency injection in the constructor, as it already happens in your code snippet.如果您需要来自 controller 中的学生实例的信息,您可以通过构造函数中的依赖注入传递它,因为它已经在您的代码片段中发生。 For this to work, IStudent must be registered with the service container.为此,必须向服务容器注册 IStudent。 This is done in Startup.cs in the ConfigureServices method:这是在 Startup.cs 的 ConfigureServices 方法中完成的:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddTransient<IStudent,Student>();
...
}
Such a service may have different lifetimes:这样的服务可能有不同的生命周期:
Depending on what lifetime you want your service to have, you need to choose the registration method accordingly.根据您希望服务拥有的生命周期,您需要相应地选择注册方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.