Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions src/System.CommandLine.Hosting.Tests/HostingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -366,5 +366,46 @@ public static void GetInvocationContext_in_ConfigureServices_throws_if_not_withi
})
.Should().Throw<InvalidOperationException>();
}

[Fact]
public static void GetHost_returns_non_null_instance_in_subsequent_middleware()
{
bool hostAsserted = false;
var parser = new CommandLineBuilder()
.UseHost()
.UseMiddleware((invCtx, next) =>
{
IHost host = invCtx.GetHost();
host.Should().NotBeNull();
hostAsserted = true;

return next(invCtx);
})
.Build();

_ = parser.Invoke(string.Empty);

hostAsserted.Should().BeTrue();
}

[Fact]
public static void GetHost_returns_null_when_no_host_in_invocation()
{
bool hostAsserted = false;
var parser = new CommandLineBuilder()
.UseMiddleware((invCtx, next) =>
{
IHost host = invCtx.GetHost();
host.Should().BeNull();
hostAsserted = true;

return next(invCtx);
})
.Build();

_ = parser.Invoke(string.Empty);

hostAsserted.Should().BeTrue();
}
}
}
7 changes: 7 additions & 0 deletions src/System.CommandLine.Hosting/HostingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,5 +138,12 @@ public static InvocationContext GetInvocationContext(this HostBuilderContext con

throw new InvalidOperationException("Host builder has no Invocation Context registered to it.");
}

public static IHost GetHost(this InvocationContext invocationContext)
{
_ = invocationContext ?? throw new ArgumentNullException(paramName: nameof(invocationContext));
var hostModelBinder = new ModelBinder<IHost>();
return (IHost)hostModelBinder.CreateInstance(invocationContext.BindingContext);
}
}
}