Skip to content

Commit

Permalink
Add InvocationContext.GetHost extension method (dotnet#1221)
Browse files Browse the repository at this point in the history
* Add InvocationContext.GetHost extension method

* Add tests for GetHost extension on InvocationContext
  • Loading branch information
fredrikhr authored Mar 27, 2021
1 parent 1f9483c commit c76213f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
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);
}
}
}

0 comments on commit c76213f

Please sign in to comment.