Add a Test singleton in StartUp.ConfigureServices

In Startup.js:

1
2
3
4
5
6
7
// This method gets called by the runtime. 
// Use this method to add services to the container.

public void ConfigureServices (IServiceCollection services) {
services.AddControllers ();
services.AddSingleton<Server.Controllers.Test>();
}

services.AddControllers (); will add all the classes that extend ControllerBase into the service collection;

services.AddSingleton will add a singleton of the class we specify.

Inject the Test singleton when Controller is constructed

1
2
3
4
public WeatherForecastController (ILogger<WeatherForecastController> logger, Test test) {
_logger = logger;
_test = test;
}

We can add as many arguments (objects) into the controller’s constructor as we need.
A WeatherForecastController object will be constructed each time a request is made. Now each time the controller is constructed, it will know about the Test object and can use it in its methods.