Skip to content

Dependency injection

Adam Bajguz edited this page Apr 5, 2021 · 3 revisions

Typin uses Microsoft.Extensions.DependencyInjection (aka the built-in dependency container in ASP.NET Core) to initialize commands and directives, and to support services injection.

Every directive, middleware, and command is registered using its interface (IDirective, ICommandMiddleware, and ICommand, respectively) implementation class with a lifetime set ot Singleton. Thus, it is possible to get an enumeration/list of all directives or commands.

Services can be registerd using ConfigureServices or UseStartup.

You can use a command to list all services in the app: source.

Typin supports also Scoped services. A scope is defined as a lifetime of a command execution pipeline that includes directives handling.

public static class Program
{
    public static async Task<int> Main()
    {
        return await new CliApplicationBuilder()
            .AddCommandsFromThisAssembly()
            .AddDirectivesFromThisAssembly()
            .ConfigureServices((services) =>
            {
                // Register services
                services.AddSingleton<MyService>();
                services.AddTransient<MyCommand>();
            })
            .UseConsole<SystemConsole>()
            .Build()
            .RunAsync();
    }
}
Clone this wiki locally