System.CommandLine is a very good parser but you need a lot of boilerplate code to get going and the API is hard to discover.
This becomes complicated to newcomers and also you would have a lot of ugly code in your Program.cs
to maintain.
What if you had an easy class-based layer combined with a good parser?
DotMake.CommandLine is a library which provides declarative syntax for System.CommandLine via attributes for easy, fast, strongly-typed (no reflection) usage. The library includes includes a source generator which automagically converts your classes to CLI commands and properties to CLI options or CLI arguments. Supports trimming, AOT compilation and dependency injection!
Install the library to your console app project with NuGet.
In your project directory, via dotnet cli:
dotnet add package DotMake.CommandLine
or in Visual Studio Package Manager Console:
PM> Install-Package DotMake.CommandLine
<LangVersion>9.0</LangVersion>
tag (minimum) in your .csproj file.dotnet
cli).Create a CLI App with DotMake.Commandline in seconds!
In Program.cs
, add this simple code:
using System;
using DotMake.CommandLine;
Cli.Run(([CliArgument]string arg1, bool opt1) =>
{
Console.WriteLine($@"Value for {nameof(arg1)} parameter is '{arg1}'");
Console.WriteLine($@"Value for {nameof(opt1)} parameter is '{opt1}'");
});
And that’s it! You now have a fully working command-line app.
Cli.Run
.CliArgument
attribute to make it a CLI argument and specify settings (see CliArgumentAttribute docs for more info).CliOption
attribute to specify CLI option settings (see CliOptionAttribute docs for more info).CliCommand
attribute to specify CLI command settings (see CliCommandAttribute docs for more info).<LangVersion>10.0</LangVersion>
tag (minimum) in your .csproj file.async
.void
or int
and if it’s async Task
or Task<int>
.While delegate-based model above is useful for simple apps, for more complex apps, you should use the class-based model because you can have sub-commands and command inheritance.
In Program.cs
, add this simple code:
using System;
using DotMake.CommandLine;
// Add this single line to run you app!
Cli.Run<RootCliCommand>(args);
// Create a simple class like this to define your root command:
[CliCommand(Description = "A root cli command")]
public class RootCliCommand
{
[CliOption(Description = "Description for Option1")]
public string Option1 { get; set; } = "DefaultForOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
public void Run()
{
Console.WriteLine($@"Handler for '{GetType().FullName}' is run:");
Console.WriteLine($@"Value for {nameof(Option1)} property is '{Option1}'");
Console.WriteLine($@"Value for {nameof(Argument1)} property is '{Argument1}'");
Console.WriteLine();
}
}
And that’s it! You now have a fully working command-line app. You just specify the name of your class which represents your root command to Cli.Run<>
method and everything is wired.
args
is the string array typically passed to a program. This is usually the special variableargs
available inProgram.cs
(new style with top-level statements) or the string array passed to the program’sMain
method (old style). We also have method signatures which does not requireargs
, for example you can also callCli.Run<RootCliCommand>()
and in that caseargs
will be retrieved automatically from the current process viaCli.GetArgs()
.
If you want to go async, just use this:
await Cli.RunAsync<RootCliCommand>(args);
To handle exceptions, you just use a try-catch block:
try
{
Cli.Run<RootCliCommand>(args);
}
catch (Exception e)
{
Console.WriteLine(@"Exception in main: {0}", e.Message);
}
System.CommandLine, by default overtakes your exceptions that are thrown in command handlers
(even if you don’t set an exception handler explicitly) but DotMake.CommandLine, by default allows
the exceptions to pass through. However if you wish, you can easily use the default exception handler
by passing a CliSettings
instance like below. Default exception handler prints the exception in red color to console:
Cli.Run<RootCliCommand>(args, new CliSettings { EnableDefaultExceptionHandler = true });
If you need to simply parse the command-line arguments without invocation, use this:
var parseResult = Cli.Parse<RootCliCommand>(args);
var rootCliCommand = parseResult.Bind<RootCliCommand>();
If you need to examine the parse result, such as errors:
var parseResult = Cli.Parse<RootCliCommand>(args);
if (parseResult.Errors.Count > 0)
{
}
CliCommand
attribute to make it a CLI command (see CliCommandAttribute docs for more info).CliOption
attribute to make it a CLI option (see CliOptionAttribute docs for more info).CliArgument
attribute to make it a CLI argument (see CliArgumentAttribute docs for more info).Add a method with name Run
or RunAsync
to make it the handler for the CLI command. The method can have one of the following signatures:
void Run()
int Run()
async Task RunAsync()
async Task<int> RunAsync()
Optionally the method signature can have a CliContext
parameter in case you need to access it:
Run(CliContext context)
-
RunAsync(CliContext context)
The signatures which return int value, sets the ExitCode of the app.
If no handler method is provided, then by default it will show help for the command.
This can be also controlled manually by extension method ShowHelp
in CliContext
.
Other extension methods IsEmptyCommand
and ShowValues
are also useful.
Cli.Run<>
orCli.RunAsync<>
method with your class name to run your CLI app (see Cli docs for more info).Commands
in your project and put your command classes there
so that they are easy to locate and maintain in the future.A command in command-line input is a token that specifies an action or defines a group of related actions. For example:
dotnet run
, run
is a command that specifies an action.dotnet tool install
, install
is a command that specifies an action, and tool
is a command that specifies a group of related commands. There are other tool-related commands, such as tool uninstall
, tool list
, and tool update
.The root command is the one that specifies the name of the app’s executable. For example, the dotnet
command specifies the dotnet.exe executable.
Most command-line apps support subcommands, also known as verbs. For example, the dotnet
command has a run
subcommand that you invoke by entering dotnet run
.
Subcommands can have their own subcommands. In dotnet tool install
, install
is a subcommand of tool
.
Defining sub-commands in DotMake.Commandline is very easy. We simply use nested classes to create a hierarchy.
Just make sure you apply CliCommand
attribute to the nested classes as well.
Command hierarchy in below example is:
RootWithNestedChildrenCliCommand
-> Level1SubCliCommand
-> Level2SubCliCommand
[CliCommand(Description = "A root cli command with nested children")]
public class RootWithNestedChildrenCliCommand
{
[CliOption(Description = "Description for Option1")]
public string Option1 { get; set; } = "DefaultForOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
public void Run(CliContext context)
{
context.ShowValues();
}
[CliCommand(Description = "A nested level 1 sub-command")]
public class Level1SubCliCommand
{
[CliOption(Description = "Description for Option1")]
public string Option1 { get; set; } = "DefaultForOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
public void Run(CliContext context)
{
context.ShowValues();
}
[CliCommand(Description = "A nested level 2 sub-command")]
public class Level2SubCliCommand
{
[CliOption(Description = "Description for Option1")]
public string Option1 { get; set; } = "DefaultForOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
public void Run(CliContext context)
{
context.ShowValues();
}
}
}
}
Another way to create hierarchy between commands, especially if you want to use standalone classes,
is to use Parent
property of CliCommand
attribute to specify typeof
parent class.
Consider you have this root command:
[CliCommand(Description = "A root cli command with external children and one nested child and testing settings inheritance")]
public class RootWithExternalChildrenCliCommand
{
[CliOption(Description = "Description for Option1")]
public string Option1 { get; set; } = "DefaultForOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
public void Run(CliContext context)
{
context.ShowValues();
}
[CliCommand(
Description = "A nested level 1 sub-command with custom settings, throws test exception",
NameCasingConvention = CliNameCasingConvention.SnakeCase,
NamePrefixConvention = CliNamePrefixConvention.ForwardSlash,
ShortFormPrefixConvention = CliNamePrefixConvention.ForwardSlash
)]
public class Level1SubCliCommand
{
[CliOption(Description = "Description for Option1")]
public string Option1 { get; set; } = "DefaultForOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
public void Run()
{
throw new Exception("This is a test exception from Level1SubCliCommand");
}
}
}
Command hierarchy in below example is:
RootWithExternalChildrenCliCommand
-> ExternalLevel1SubCliCommand
-> Level2SubCliCommand
[CliCommand(
Description = "An external level 1 sub-command",
Parent = typeof(RootWithExternalChildrenCliCommand)
)]
public class ExternalLevel1SubCliCommand
{
[CliOption(Description = "Description for Option1")]
public string Option1 { get; set; } = "DefaultForOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
public void Run(CliContext context)
{
context.ShowValues();
}
[CliCommand(Description = "A nested level 2 sub-command")]
public class Level2SubCliCommand
{
[CliOption(Description = "Description for Option1")]
public string Option1 { get; set; } = "DefaultForOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
public void Run(CliContext context)
{
context.ShowValues();
}
}
}
Command hierarchy in below example is:
RootWithExternalChildrenCliCommand
-> Level1SubCliCommand
-> ExternalLevel2SubCliCommand
-> Level3SubCliCommand
[CliCommand(
Description = "An external level 2 sub-command",
Parent = typeof(RootWithExternalChildrenCliCommand.Level1SubCliCommand),
NameCasingConvention = CliNameCasingConvention.SnakeCase,
NamePrefixConvention = CliNamePrefixConvention.ForwardSlash,
ShortFormPrefixConvention = CliNamePrefixConvention.ForwardSlash
)]
public class ExternalLevel2SubCliCommand
{
[CliOption(Description = "Description for Option1")]
public string Option1 { get; set; } = "DefaultForOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
public void Run(CliContext context)
{
context.ShowValues();
}
[CliCommand(Description = "A nested level 3 sub-command")]
public class Level3SubCliCommand
{
[CliOption(Description = "Description for Option1")]
public string Option1 { get; set; } = "DefaultForOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
public void Run(CliContext context)
{
context.ShowValues();
}
}
}
The class that CliCommand
attribute is applied to,
Parent
property is not set.Parent
property is set.Sub-commands can get a reference to the parent command by adding a property of the parent command type.
Alternatively ParseResult.Bind<TDefinition>
method can be called to manually get reference to a parent command.
Note that binding will be done only once per definition class, so calling this method consecutively
for the same definition class will return the cached result.
// Sub-commands can get a reference to the parent command by adding a property of the parent command type.
[CliCommand(Description = "A root cli command with children that can access parent commands")]
public class ParentCommandAccessorCliCommand
{
[CliOption(
Description = "This is a global option (Recursive option on the root command), it can appear anywhere on the command line",
Recursive = true)]
public string GlobalOption1 { get; set; } = "DefaultForGlobalOption1";
[CliArgument(Description = "Description for RootArgument1")]
public string RootArgument1 { get; set; }
public void Run(CliContext context)
{
context.ShowValues();
}
[CliCommand(Description = "A nested level 1 sub-command which accesses the root command")]
public class Level1SubCliCommand
{
[CliOption(
Description = "This is global for all sub commands (it can appear anywhere after the level-1 verb)",
Recursive = true)]
public string Level1RecursiveOption1 { get; set; } = "DefaultForLevel1RecusiveOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
// The parent command gets automatically injected
public ParentCommandAccessorCliCommand RootCommand { get; set; }
public void Run(CliContext context)
{
context.ShowValues();
}
[CliCommand(Description = "A nested level 2 sub-command which accesses its parent commands")]
public class Level2SubCliCommand
{
[CliOption(Description = "Description for Option1")]
public string Option1 { get; set; } = "DefaultForOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
// All ancestor commands gets injected
public ParentCommandAccessorCliCommand RootCommand { get; set; }
public Level1SubCliCommand ParentCommand { get; set; }
public void Run(CliContext context)
{
context.ShowValues();
Console.WriteLine();
Console.WriteLine(@$"Level1RecursiveOption1 = {ParentCommand.Level1RecursiveOption1}");
Console.WriteLine(@$"parent Argument1 = {ParentCommand.Argument1}");
Console.WriteLine(@$"GlobalOption1 = {RootCommand.GlobalOption1}");
Console.WriteLine(@$"RootArgument1 = {RootCommand.RootArgument1}");
}
}
}
}
When you have repeating/common options and arguments for your commands, you can define them once in a base class and then share them by inheriting that base class in other command classes. Interfaces are also supported !
[CliCommand]
public class InheritanceCliCommand : CredentialCommandBase, IDepartmentCommand
{
public string Department { get; set; } = "Accounting";
}
public abstract class CredentialCommandBase
{
[CliOption(Description = "Username of the identity performing the command")]
public string Username { get; set; } = "admin";
[CliOption(Description = "Password of the identity performing the command")]
public string Password { get; set; }
public void Run()
{
Console.WriteLine($@"I am {Username}");
}
}
public interface IDepartmentCommand
{
[CliOption(Description = "Department of the identity performing the command (interface)")]
string Department { get; set; }
}
The property attribute and the property initializer from the most derived class in the hierarchy will be used
(they will override the base ones). The command handler (Run or RunAsync) will be also inherited.
So in the above example, InheritanceCliCommand
inherits options Username
, Password
from a base class and
option Department
from an interface. Note that the property initializer for Department
is in the derived class,
so that default value will be used.
The properties for CliCommand
attribute (see CliCommandAttribute docs for more info):
An option is a named parameter that can be passed to a command. POSIX CLIs typically prefix the option name with two hyphens (--
). The following example shows two options:
dotnet tool update dotnet-suggest --verbosity quiet --global
^---------^ ^------^
As this example illustrates, the value of the option may be explicit (quiet
for --verbosity
) or implicit (nothing follows --global
). Options that have no value specified are typically Boolean parameters that default to true
if the option is specified on the command line.
For some Windows command-line apps, you identify an option by using a leading slash (/
) with the option name. For example:
msbuild /version
^------^
Both POSIX and Windows prefix conventions are supported.
When manually setting a name (overriding decorated property’s name), you should specify the option name including the prefix (e.g. --option
, -option
or /option
)
The properties for CliOption
attribute (see CliOptionAttribute docs for more info):
An argument is a value passed to an option or a command. The following examples show an argument for the verbosity
option and an argument for the build
command.
dotnet tool update dotnet-suggest --verbosity quiet --global
^---^
dotnet build myapp.csproj
^----------^
Arguments can have default values that apply if no argument is explicitly provided. For example, many options are implicitly Boolean parameters with a default of true
when the option name is in the command line. The following command-line examples are equivalent:
dotnet tool update dotnet-suggest --global
^------^
dotnet tool update dotnet-suggest --global true
^-----------^
Some options have required arguments. For example in the .NET CLI, --output
requires a folder name argument. If the argument is not provided, the command fails.
Arguments can have expected types, and System.CommandLine
displays an error message if an argument can’t be parsed into the expected type. For example, the following command errors because “silent” isn’t one of the valid values for --verbosity
:
dotnet build --verbosity silent
Cannot parse argument 'silent' for option '-v' as expected type 'Microsoft.DotNet.Cli.VerbosityOptions'. Did you mean one of the following?
Detailed
Diagnostic
Minimal
Normal
Quiet
The properties for CliArgument
attribute (see CliArgumentAttribute docs for more info):
When the command handler is run, the properties for CLI options and arguments will be already populated and bound from values passed in the command-line. If no matching value is passed, the property will have its default value if it has one or an error will be displayed if it’s a required option/argument and it was not specified on the command-line.
An option/argument will be considered required when
public string Arg { get; set; }
).
string
is a reference type which has a null as the default value but bool
and enum
are value
types which already have non-null default values. Nullable<T>
is a reference type, e.g. bool?
.null
or null!
(SuppressNullableWarningExpression)
(e.g. public string Arg { get; set; } = null!;
).Required
(e.g. [CliArgument(Required = true)]
).required
modifier (e.g. public required string Opt { get; set; }
).
Note that for being able to use required
modifier, if your target framework is below net7.0,
you also need <LangVersion>11.0</LangVersion>
tag (minimum) in your .csproj file (our source generator supplies the polyfills
automatically as long as you set C# language version to 11).An option/argument will be considered optional when
public bool Opt { get; set; }
) but the property type is a value type
which already have non-null default value.null
or null!
(SuppressNullableWarningExpression)
(e.g. public string Arg { get; set; } = "Default";
).Required
(e.g. [CliArgument(Required = false)]
).When you run,
TestApp.exe NewValueForArgument1
or (note the double hyphen/dash which allows dotnet run
to pass arguments to our actual application):
dotnet run -- NewValueForArgument1
You see this result:
Handler for 'TestApp.Commands.RootCliCommand' is run:
Value for Option1 property is 'DefaultForOption1'
Value for Argument1 property is 'NewValueForArgument1'
Note that you can have a specific type (other than string
) for a property which a CliOption
or CliArgument
attribute is applied to, for example these properties will be parsed and bound/populated automatically:
[CliCommand]
public class WriteFileCommand
{
[CliArgument]
public FileInfo OutputFile { get; set; }
[CliOption]
public List<string> Lines { get; set; }
}
The following types for properties are supported:
true
or false
is passed for an option having a bool
argument, it is parsed and bound as expected.
But an option whose argument type is bool
doesn’t require an argument to be specified.
The presence of the option token on the command line, with no argument following it, results in a value of true
.Common CLR types:
FileSystemInfo
, FileInfo
, DirectoryInfo
int
, long
, short
, uint
, ulong
, ushort
double
, float
, decimal
byte
, sbyte
DateTime
, DateTimeOffset
, TimeSpan
, DateOnly
, TimeOnly
Guid
Uri
, IPAddress
, IPEndPoint
Parse
method with a string parameter (other parameters, if any, should be optional) - These types can be bound/parsed
automatically even if they are wrapped with Enumerable
or Nullable
type.
[CliCommand]
public class ArgumentConverterCliCommand
{
[CliOption]
public ClassWithConstructor Opt { get; set; }
[CliOption(AllowMultipleArgumentsPerToken = true)]
public ClassWithConstructor[] OptArray { get; set; }
[CliOption]
public CustomStruct? OptNullable { get; set; }
[CliOption]
public IEnumerable<ClassWithConstructor> OptEnumerable { get; set; }
[CliOption]
public List<ClassWithConstructor> OptList { get; set; }
[CliOption]
public CustomList<ClassWithConstructor> OptCustomList { get; set; }
[CliArgument]
public IEnumerable<ClassWithParser> Arg { get; set; }
}
public class ClassWithConstructor
{
private readonly string value;
public ClassWithConstructor(string value)
{
this.value = value;
}
public override string ToString()
{
return value;
}
}
public class ClassWithParser
{
private string value;
public override string ToString()
{
return value;
}
public static ClassWithParser Parse(string value)
{
var instance = new ClassWithParser();
instance.value = value;
return instance;
}
}
public struct CustomStruct
{
private readonly string value;
public CustomStruct(string value)
{
this.value = value;
}
public override string ToString()
{
return value;
}
}
Arrays, lists, collections:
Any type that implements IEnumerable<T>
and has a public constructor with a IEnumerable<T>
or IList<T>
parameter
(other parameters, if any, should be optional). CLR collection types already satisfy this condition.
If type is generic IEnumerable<T>
, IList<T>
, ICollection<T>
interfaces itself, array T[]
will be used to create an instance.
If type is non-generic IEnumerable
, IList
, ICollection
interfaces itself, array string[]
will be used to create an instance.
[CliCommand]
public class EnumerableCliCommand
{
[CliOption]
public IEnumerable<int> OptEnumerable { get; set; }
[CliOption]
public List<string> OptList { get; set; }
[CliOption(AllowMultipleArgumentsPerToken = true)]
public FileAccess[] OptEnumArray { get; set; }
[CliOption]
public Collection<string> OptCollection { get; set; }
[CliOption]
public HashSet<string> OptHashSet { get; set; }
[CliOption]
public Queue<FileInfo> OptQueue { get; set; }
[CliOption]
public CustomList<string> OptCustomList { get; set; }
[CliArgument]
public IList ArgIList { get; set; }
}
public class CustomList<T> : List<T>
{
public CustomList(IEnumerable<T> items)
: base(items)
{
}
}
In [CliOption]
and [CliArgument]
attributes;
ValidationRules
property allows setting predefined validation rules such as
CliValidationRules.ExistingFile
CliValidationRules.NonExistingFile
CliValidationRules.ExistingDirectory
CliValidationRules.NonExistingDirectory
CliValidationRules.ExistingFileOrDirectory
CliValidationRules.NonExistingFileOrDirectory
CliValidationRules.LegalPath
CliValidationRules.LegalFileName
CliValidationRules.LegalUri
CliValidationRules.LegalUrl
Validation rules can be combined via using bitwise ‘or’ operator(|
in C#).
ValidationPattern
property allows setting a regular expression pattern for custom validation,
and ValidationMessage
property allows setting a custom error message to show when ValidationPattern
does not match.
[CliCommand]
public class ValidationCliCommand
{
[CliOption(Required = false, ValidationRules = CliValidationRules.ExistingFile)]
public FileInfo OptFile1 { get; set; }
[CliOption(Required = false, ValidationRules = CliValidationRules.NonExistingFile | CliValidationRules.LegalPath)]
public string OptFile2 { get; set; }
[CliOption(Required = false, ValidationPattern = @"(?i)^[a-z]+$")]
public string OptPattern1 { get; set; }
[CliOption(Required = false, ValidationPattern = @"(?i)^[a-z]+$", ValidationMessage = "Custom error message")]
public string OptPattern2 { get; set; }
[CliOption(Required = false, ValidationRules = CliValidationRules.LegalUrl)]
public string OptUrl { get; set; }
[CliOption(Required = false, ValidationRules = CliValidationRules.LegalUri)]
public string OptUri { get; set; }
[CliArgument(Required = false, ValidationRules = CliValidationRules.LegalFileName)]
public string OptFileName { get; set; }
public void Run(CliContext context)
{
context.ShowValues();
}
}
Commands can have injected dependencies, this is supported via Microsoft.Extensions.DependencyInjection
package (version >= 2.1.1).
In your project directory, via dotnet cli:
dotnet add package Microsoft.Extensions.DependencyInjection
or in Visual Studio Package Manager Console:
PM> Install-Package Microsoft.Extensions.DependencyInjection
When the source generator detects that your project has reference to Microsoft.Extensions.DependencyInjection
,
it will generate extension methods for supporting dependency injection.
For example, you can now add your services with the extension method Cli.Ext.ConfigureServices
:
using DotMake.CommandLine;
using Microsoft.Extensions.DependencyInjection;
Cli.Ext.ConfigureServices(services =>
{
services.AddTransient<TransientClass>();
services.AddScoped<ScopedClass>();
services.AddSingleton<SingletonClass>();
});
Cli.Run<RootCliCommand>();
Then let them be injected to your command class automatically by providing a constructor with the required services:
[CliCommand(Description = "A root cli command with dependency injection")]
public class RootCliCommand
{
private readonly TransientClass transientDisposable;
private readonly ScopedClass scopedDisposable;
private readonly SingletonClass singletonDisposable;
public RootCliCommand(
TransientClass transientDisposable,
ScopedClass scopedDisposable,
SingletonClass singletonDisposable
)
{
this.transientDisposable = transientDisposable;
this.scopedDisposable = scopedDisposable;
this.singletonDisposable = singletonDisposable;
}
[CliOption(Description = "Description for Option1")]
public string Option1 { get; set; } = "DefaultForOption1";
[CliArgument(Description = "Description for Argument1")]
public string Argument1 { get; set; }
public void Run()
{
Console.WriteLine($@"Handler for '{GetType().FullName}' is run:");
Console.WriteLine($@"Value for {nameof(Option1)} property is '{Option1}'");
Console.WriteLine($@"Value for {nameof(Argument1)} property is '{Argument1}'");
Console.WriteLine();
Console.WriteLine($"Instance for {transientDisposable.Name} is available");
Console.WriteLine($"Instance for {scopedDisposable.Name} is available");
Console.WriteLine($"Instance for {singletonDisposable.Name} is available");
Console.WriteLine();
}
}
public sealed class TransientClass : IDisposable
{
public string Name => nameof(TransientClass);
public void Dispose() => Console.WriteLine($"{nameof(TransientClass)}.Dispose()");
}
public sealed class ScopedClass : IDisposable
{
public string Name => nameof(ScopedClass);
public void Dispose() => Console.WriteLine($"{nameof(ScopedClass)}.Dispose()");
}
public sealed class SingletonClass : IDisposable
{
public string Name => nameof(SingletonClass);
public void Dispose() => Console.WriteLine($"{nameof(SingletonClass)}.Dispose()");
}
Other dependency injection containers (e.g. Autofac) are also supported
via Microsoft.Extensions.DependencyInjection.Abstractions
package (version >= 2.1.1).
In your project directory, via dotnet cli:
dotnet add package Microsoft.Extensions.DependencyInjection.Abstractions
or in Visual Studio Package Manager Console:
PM> Install-Package Microsoft.Extensions.DependencyInjection.Abstractions
When the source generator detects that your project has reference to Microsoft.Extensions.DependencyInjection.Abstractions
,
it will generate extension methods for supporting custom service providers.
For example, you can now set your custom service provider with the extension method Cli.Ext.SetServiceProvider
:
using DotMake.CommandLine;
using Autofac.Core;
using Autofac.Core.Registration;
var cb = new ContainerBuilder();
cb.RegisterType<object>();
var container = cb.Build();
Cli.Ext.SetServiceProvider(container);
Cli.Run<RootCliCommand>();
When you run the app via
TestApp.exe -?
in project output path (e.g. in TestApp\bin\Debug\net7.0
)or dotnet run -- -?
in project directory (e.g. in TestApp
) (note the double hyphen/dash which allows dotnet run
to pass arguments to our actual application)
A root cli command
Usage:
TestApp
Arguments: