static async Task <int> Main(string[] args) { // We don't have access to a built host yet. Get configuration settings using a configuration builder. // Required to set initial token credentials. var configBuilder = new ConfigurationBuilder(); ConfigureAppConfiguration(configBuilder); var config = configBuilder.Build(); var authSettings = config.GetSection(nameof(AuthenticationOptions)).Get <AuthenticationOptions>(); var authServiceFactory = new AuthenticationServiceFactory(new PathUtility()); var authStrategy = AuthenticationStrategy.DeviceCode; var credential = await authServiceFactory.GetTokenCredentialAsync(authStrategy, authSettings?.TenantId, authSettings?.ClientId); var authProvider = new AzureIdentityAuthenticationProvider(credential, new string[] { "graph.microsoft.com" }); var assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version; var options = new GraphClientOptions { GraphProductPrefix = "graph-cli", GraphServiceLibraryClientVersion = $"{assemblyVersion.Major}.{assemblyVersion.Minor}.{assemblyVersion.Build}", GraphServiceTargetVersion = "1.0" }; using var httpClient = GraphCliClientFactory.GetDefaultClient(options); var core = new HttpClientRequestAdapter(authProvider, httpClient: httpClient); var client = new GraphClient(core); var commands = new List <Command>(); var loginCommand = new LoginCommand(authServiceFactory); commands.Add(loginCommand.Build()); var logoutCommand = new LogoutCommand(new LogoutService()); commands.Add(logoutCommand.Build()); var builder = BuildCommandLine(client, commands).UseDefaults().UseHost(CreateHostBuilder); builder.AddMiddleware((invocation) => { var host = invocation.GetHost(); var outputFilter = host.Services.GetRequiredService <IOutputFilter>(); var outputFormatterFactory = host.Services.GetRequiredService <IOutputFormatterFactory>(); invocation.BindingContext.AddService <IOutputFilter>(_ => outputFilter); invocation.BindingContext.AddService <IOutputFormatterFactory>(_ => outputFormatterFactory); }); builder.UseExceptionHandler((ex, context) => { if (ex is AuthenticationRequiredException) { Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Red; context.Console.Error.WriteLine("Token acquisition failed. Run mgc login command first to get an access token."); Console.ResetColor(); } else { Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Red; context.Console.Error.WriteLine(ex.Message); context.Console.Error.WriteLine(ex.StackTrace); Console.ResetColor(); } }); var parser = builder.Build(); return(await parser.InvokeAsync(args)); }