Minor improvements to dependency injection example (#1)

* Update code example to align with snippet in CommandApp/DI documentation

* Renamed TypeRegistrar to MyTypeRegistrar, making it more obvious it is a custom class the user must provide.
This commit is contained in:
Frank Ray
2025-04-08 16:00:31 +01:00
committed by GitHub
parent b030977c0a
commit f113d9fb02
3 changed files with 9 additions and 8 deletions

View File

@@ -4,18 +4,18 @@ using Spectre.Console.Cli;
namespace Injection.Infrastructure; namespace Injection.Infrastructure;
public sealed class TypeRegistrar : ITypeRegistrar public sealed class MyTypeRegistrar : ITypeRegistrar
{ {
private readonly IServiceCollection _builder; private readonly IServiceCollection _builder;
public TypeRegistrar(IServiceCollection builder) public MyTypeRegistrar(IServiceCollection builder)
{ {
_builder = builder; _builder = builder;
} }
public ITypeResolver Build() public ITypeResolver Build()
{ {
return new TypeResolver(_builder.BuildServiceProvider()); return new MyTypeResolver(_builder.BuildServiceProvider());
} }
public void Register(Type service, Type implementation) public void Register(Type service, Type implementation)

View File

@@ -3,11 +3,11 @@ using Spectre.Console.Cli;
namespace Injection.Infrastructure; namespace Injection.Infrastructure;
public sealed class TypeResolver : ITypeResolver, IDisposable public sealed class MyTypeResolver : ITypeResolver, IDisposable
{ {
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public TypeResolver(IServiceProvider provider) public MyTypeResolver(IServiceProvider provider)
{ {
_provider = provider ?? throw new ArgumentNullException(nameof(provider)); _provider = provider ?? throw new ArgumentNullException(nameof(provider));
} }

View File

@@ -9,11 +9,12 @@ public class Program
{ {
public static int Main(string[] args) public static int Main(string[] args)
{ {
// Create a type registrar and register any dependencies.
// A type registrar is an adapter for a DI framework.
var registrations = new ServiceCollection(); var registrations = new ServiceCollection();
registrations.AddSingleton<IGreeter, HelloWorldGreeter>(); registrations.AddSingleton<IGreeter, HelloWorldGreeter>();
var registrar = new TypeRegistrar(registrations);
// Create a type registrar and register any dependencies.
// A type registrar is an adapter for a DI framework.
var registrar = new MyTypeRegistrar(registrations);
// Create a new command app with the registrar // Create a new command app with the registrar
// and run it with the provided arguments. // and run it with the provided arguments.