Register the console lazily in CLI type registrar

This should fix a strange bug we're seeing in Cake on macOS.
This commit is contained in:
Patrik Svensson 2021-02-12 00:02:59 +01:00 committed by Patrik Svensson
parent fd217ffc83
commit 28e9c14de4
5 changed files with 47 additions and 1 deletions

View File

@ -27,5 +27,15 @@ namespace Injection
{
_builder.AddSingleton(service, implementation);
}
public void RegisterLazy(Type service, Func<object> func)
{
if (func is null)
{
throw new ArgumentNullException(nameof(func));
}
_builder.AddSingleton(service, (provider) => func());
}
}
}

View File

@ -37,6 +37,19 @@ namespace Spectre.Console.Testing
}
}
public void RegisterLazy(Type service, Func<object> factory)
{
if (factory is null)
{
throw new ArgumentNullException(nameof(factory));
}
if (!Instances.ContainsKey(service))
{
Instances.Add(service, new List<object> { factory() });
}
}
public ITypeResolver Build()
{
return _resolver;

View File

@ -21,6 +21,13 @@ namespace Spectre.Console.Cli
/// <param name="implementation">The implementation.</param>
void RegisterInstance(Type service, object implementation);
/// <summary>
/// Registers the specified instance lazily.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="factory">The factory that creates the implementation.</param>
void RegisterLazy(Type service, Func<object> factory);
/// <summary>
/// Builds the type resolver representing the registrations
/// specified in the current instance.

View File

@ -24,7 +24,7 @@ namespace Spectre.Console.Cli
}
_registrar.RegisterInstance(typeof(IConfiguration), configuration);
_registrar.RegisterInstance(typeof(IAnsiConsole), configuration.Settings.Console.GetConsole());
_registrar.RegisterLazy(typeof(IAnsiConsole), () => configuration.Settings.Console.GetConsole());
// Create the command model.
var model = CommandModelBuilder.Build(configuration);

View File

@ -35,5 +35,21 @@ namespace Spectre.Console.Cli
var registration = new ComponentRegistration(service, new CachingActivator(new InstanceActivator(implementation)));
_registry.Enqueue(registry => registry.Register(registration));
}
public void RegisterLazy(Type service, Func<object> factory)
{
if (factory is null)
{
throw new ArgumentNullException(nameof(factory));
}
_registry.Enqueue(registry =>
{
var activator = new CachingActivator(new InstanceActivator(factory()));
var registration = new ComponentRegistration(service, activator);
registry.Register(registration);
});
}
}
}