2

My goal is to use arguments from the command line (namely, a username + token) later in one of the controllers.

  • This blog explained a lot of useful setup, but not how to actually use custom arguments other than --environment.
  • I've found ways to pass command line arguments into the Startup class, but not how to get it into the controller.
  • Upon looking at the docs, I cannot correctly pass the parameters to controller classes (the sample file also conflates the Program and Startup classes, so I am not sure how to handle that in my own code).

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.

janezdu
  • 48
  • 1
  • 8
  • That makes sense, but I'd like to allow someone else to deploy the web app from the command line with `donet myapp.dll`, without having to go in and modiify files. Is this an OK approach? (Also not sure if relevant, but I'm not running in IIS Express, but a custom docker container) – janezdu Jun 27 '17 at 16:59
  • How are you hosting? Self hosted? IIS? Owin? –  Jun 27 '17 at 16:59
  • @Amy Self-hosting in a docker container. It's not the one that Visual Studio generates automatically though, I've written my own Dockerfile, etc. Ideally someone will type `docker run -e "USERNAME=un" image` and the container will run this app using the username passed in. – janezdu Jun 27 '17 at 17:32

1 Answers1

1

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
    }
}
Set
  • 47,577
  • 22
  • 132
  • 150