.Net Core Console Applications with Dependency Injection

  1. Support of dependency injection via Microsoft.Extensions.DependencyInjection
  2. Robust command line argument parsing using CommandLine
  3. Logging independently of Console I/O using Serilog

Application Structure

  1. Configuring services for the application
  2. Parsing command line arguments and generate task factory to execute the desired command
  3. Executing the task and exit indicating success or failure
Structure for a Dependency Injected Console Application

Command Line Parsing

Arguments for the “calc” verb
Using CommnadLineParser to Configure Tasks

Setting up Task Factories

A Simple Factory to Launch a Task
  1. Create a task factory implementing ITaskFactory in ConfigureServices
  2. Launch a task using the task factory after we’ve configured everything
Configuring a Task Factory and Launch a Task


Example Task to Evaluate a Mathematical Expression


  • dotnet run -- 100 + 200 / 2 (Returns 200)
  • dotnet run -- "(100 + 200) / 2" (Returns 150, you’ll need the quotes for parenthesis and asterisks)
  • dotnet run -- calc 500 + 2 (Returns 502, the “calc” is unnecessary but shown for completeness)
  • dotnet run -- -f json 100/2 (Returns {Value”:50})
  • dotnet run -- stats 100 200 300 400 500 (Returns Count=5, Mean=300, Variance=25000, StandardDeviation=158.11388300841898, Skewness=0, Kurtosis=-1.2000000000000002, Maximum=500, Minimum=100)



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store