Class DependencyInjectionTypeRegistrar
- Namespace
- Ploch.CommandLine.Spectre.DependencyInjection
- Assembly
- Ploch.CommandLine.Spectre.dll
Provides an implementation of Spectre.Console's Spectre.Console.Cli.ITypeRegistrar that integrates with Microsoft.Extensions.DependencyInjection for dependency injection.
public sealed class DependencyInjectionTypeRegistrar : ITypeRegistrar
- Inheritance
-
DependencyInjectionTypeRegistrar
- Implements
-
ITypeRegistrar
- Inherited Members
Remarks
Lifetimes follow one rule. Everything registered through Register(Type, Type) — which is how Spectre registers every command, settings type, type converter and pair deconstructor — is transient: a new instance is created for every resolution, so a command holds its transient dependencies for its own lifetime rather than the host's. Dependency lifetimes are unchanged, so singleton services stay shared. RegisterInstance(Type, object) and RegisterLazy(Type, Func<object>?) are singletons, because that is what Spectre's contract asks for: the first must hand back the very instance it was given, and the second describes a lazily created instance: the first instance the factory creates successfully is shared by every later resolution, while a factory that throws is run again on the next resolution, because the container caches only a created instance.
The infrastructure the library registers itself — the console, the IOutput, the message formatter
processor and the application's CancellationTokenSource — stays singleton by design: those
are shared or stateless, and a command is meant to receive the same instance the application uses.
Spectre registers its types when the application runs, after every ConfigureServices delegate, and
the last registration of a service type wins. Registering a command type as a singleton from
ConfigureServices therefore has no effect; state that must outlive one resolution belongs in a
singleton service the command depends on.
Constructors
- DependencyInjectionTypeRegistrar(IHostBuilder)
Provides an implementation of Spectre.Console's Spectre.Console.Cli.ITypeRegistrar that integrates with Microsoft.Extensions.DependencyInjection for dependency injection.
Methods
- Build()
Builds and returns a type resolver that can resolve types from the configured service provider.
- Register(Type, Type)
Registers a service type with its corresponding implementation type as a transient service, so every resolution creates a new instance.
- RegisterInstance(Type, object)
Registers an existing instance as a singleton service, so every resolution returns that very instance, as Spectre's contract requires.
- RegisterLazy(Type, Func<object>?)
Registers a factory function that will be invoked to create an instance of the service when needed. The result is a lazily created singleton: the factory runs on the first resolution and every later resolution returns the same instance.