command-line-api icon indicating copy to clipboard operation
command-line-api copied to clipboard

Ensure that all services registered with Host are available.

Open aetos382 opened this issue 2 years ago • 1 comments

I wrote the following code.

return new CliConfiguration(rootCommand)
    .UseHost(
        hostBuilderFactory: Host.CreateDefaultBuilder,
        configureHost: static hostBuilder =>
        {
            hostBuilder.ConfigureServices(static (context, services) =>
            {
                // configure additional services
            });
        })
    .Invoke(args);

Host.CreateDefaultBuilder registers many useful services, but they are not copied into the BindingContext. Only services registered with configureHost are copied into BindingContext and injected into the command handler. So, for example, ILogger<T> cannot be used in a command handler unless I register it again. I don't want to repeat what CreateDefaultBuilder does.

What design decision is this behavior based on?

aetos382 avatar Jul 26 '23 09:07 aetos382

I've just run into this as well.

I've been unable to get injection of ILogger<T> working though. I can get ILoggerFactory injected by re-registering through services.AddSingleton<ILoggerFactory, LoggerFactory>();

I tried re-registering the ILogger<T> with services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));

but can't get it working as it always comes through as null.

How are you re-registering the ILogger<T> please?

barrygiles avatar Mar 27 '24 00:03 barrygiles