ASP.NET
Core Development
▌Introduction
Sometimes
we want to run the same project at local as two or more processes that each of
them has different port and environment variable.
The best
way is to containerize your application.
However, if you want a quick solution in order to do some simple tests in this scenario, we can use dotnet CLI and a few setups to achieve it.
▌Environment
▋Visual Studio 2019 Community
▌Implement
Here are
2 tips of dotnet CLI to run a project as multiple processes with different port
and environment variable.
▋
1.Launch profiles
The launchSettings.json
file describes how the application launches by specified URL, port,
environment variables, etc.
We can define multiple
launch profile in that file. For example, we have 2 launch profiles in the following
launchSettings.json,
"Demo.Client1" and "Demo.Client2".
Now we can switch
different launch profile when execute "dotnet run".
$ dotnet run --launch-profile Demo.Client1
Notice
that the above command will BUILD THE PROJECT and put the built binaries to "/bin/Debug/". If we modify the code and run another "dotnet
run –launch-profile Demo.Client2", it will cause the following
error:
The process cannot
access the file '…\src\Demo.Client\bin\Debug\net5.0\Demo.Client.exe' because
it is being used by another process. […\src\Demo.Client\Demo.Client.csproj] |
We can
specified the "--configuration|-c" argument to build and put the binaries
in different path.
For
example, it is safe to run 2 processes like this:
$ dotnet run --configuration client1 --launch-profile Demo.Client1
$ dotnet run --configuration client2 --launch-profile Demo.Client2
And the
binaries will be put at "bin\client1" and "bin\client2".
$ ls Demo.Client\bin\
client1/ client2/
▋2.Passing program arguments
The other tip to
use the program arguments.
Since we can set
the Kestrel web-server’s options by config file or by WebHostBuilderKestrelExtensions.ConfigureKestrel
Method (See Configure
options for the ASP.NET Core Kestrel web server), we can take the program
arguments and then set the custom configuration for each process.
For example, I
want to run the same project in 2 processes with different port and different
values of environment variable "ASPNETCORE_ENVIRONMENT".
$ cd Demo.Client\bin\Debug\net5.0
$ dotnet Demo.Client.dll --urls https://localhost:5001 --env Client1
$ dotnet Demo.Client.dll --urls https://localhost:5003 --env Client2
The "--urls" is a default argument of "dotnet run"
that will set the listening URL of Kestrel webserver. "--env"
is the custom argument that we will catch and update the "ASPNETCORE_ENVIRONMENT"
value in our application.
▌Reference
▋Configure
options for the ASP.NET Core Kestrel web server