My goal is to use arguments from the command line (namely, a username + token) later in one of the controllers.
--environment
. Ultimately I need to have some value configured at the beginning of the app, and this value needs to be accessed by controller methods later. Any alternatives that achieve this are also greatly appreciated.
ASP.NET Core is shipped with built-in DI container , that should be used for dependency resolving via constructor parameters.
I've found ways to pass command line arguments into the Startup class , but not how to get it into the controller.
This example already has everything that you need. See:
.ConfigureServices(services => services
.AddSingleton(new ConsoleArgs(args))
this line register ConsoleArgs
instance as a Singleton to DI container. Then it could be used as the dependency in any class. Like into Startup
class in linked example:
// args will be resolved using DI container
public Startup(IHostingEnvironment env, ConsoleArgs args)
{
...
So in case of your controller class do the same:
public class YourController : Controller
{
public YourController(ConsoleArgs args)
{
//use args here or store it in private variable
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.