-
Notifications
You must be signed in to change notification settings - Fork 0
Add Consolix
NOTE: If you intend to use only colored output helpers, input helpers and spinner/progress bar, you can do that in any type of console application right from standard Visual Studio Console application template code, just add reference to Consolix and use its extensions methods.
This below is only when you intend to use also Commands and argument parsing features.
After host-based template is created, now is the time to add Consolix commands to the picture.
First add reference to Consolix NuGet package.
NOTE: Namespace to import is Salix.Extensions
. This is to avoid namespace and class name collision and allow to use System.Console
namespace along with Consolix
.
Then append some more lines to Program.cs
file as shown here (resulting contents):
using Salix.Extensions;
public class Program
{
public static async Task<int> Main(string[] args)
{
// Set color scheme for Console application
Consolix.SetColorScheme(ConsoleColorScheme.Campbell);
IHost? host = Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
})
// Wire up Dependency injection container
.UseConsoleLifetime()
.ConfigureServices((context, collection) => SetupContainer(context, collection))
.Build();
try
{
var consoleOperationHandler = host.Services.GetRequiredService<ConsoleOperationHandler>();
consoleOperationHandler.PrepareOperation(args); // selects chosen (or the only) operation and populates its parameters (if any)
if (args.Contains("--h") || args.Contains("--help"))
{
consoleOperationHandler.OutputHelp(
typeof(Program).Assembly.GetName().Name,
"This is my cool console application.");
return 0;
}
// If we have chosen operation and it has all data it needs, invoke it.
if (consoleOperationHandler.SelectedOperation is { IsReady: true })
{
// Here operation is called to do its work.
return await consoleOperationHandler.SelectedOperation.DoWork();
}
// Fallback to displaying Help.
consoleOperationHandler.OutputHelp(
typeof(Program).Assembly.GetName().Name,
"This is my cool console application.");
return -1;
}
catch (Exception ex)
{
// Let consolix output error in red color!
Consolix.WriteLine(ex.Message, ConsoleColor.Red);
return -1;
}
}
private static void SetupContainer(HostBuilderContext context, IServiceCollection services)
{
// <--- These are your commands
services.AddTransient<IConsoleOperation, MyCommandOne>();
services.AddTransient<IConsoleOperation, MyCommandTwo>();
// --> Commands define ends here
// This here will handle the command(s) execution
services.AddTransient<ConsoleOperationHandler>();
}
}
Ready-made empty VS Solution template: ConsoleTool