Skip to content

Commit c76213f

Browse files
authored
Add InvocationContext.GetHost extension method (#1221)
* Add InvocationContext.GetHost extension method * Add tests for GetHost extension on InvocationContext
1 parent 1f9483c commit c76213f

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/System.CommandLine.Hosting.Tests/HostingTests.cs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,5 +366,46 @@ public static void GetInvocationContext_in_ConfigureServices_throws_if_not_withi
366366
})
367367
.Should().Throw<InvalidOperationException>();
368368
}
369+
370+
[Fact]
371+
public static void GetHost_returns_non_null_instance_in_subsequent_middleware()
372+
{
373+
bool hostAsserted = false;
374+
var parser = new CommandLineBuilder()
375+
.UseHost()
376+
.UseMiddleware((invCtx, next) =>
377+
{
378+
IHost host = invCtx.GetHost();
379+
host.Should().NotBeNull();
380+
hostAsserted = true;
381+
382+
return next(invCtx);
383+
})
384+
.Build();
385+
386+
_ = parser.Invoke(string.Empty);
387+
388+
hostAsserted.Should().BeTrue();
389+
}
390+
391+
[Fact]
392+
public static void GetHost_returns_null_when_no_host_in_invocation()
393+
{
394+
bool hostAsserted = false;
395+
var parser = new CommandLineBuilder()
396+
.UseMiddleware((invCtx, next) =>
397+
{
398+
IHost host = invCtx.GetHost();
399+
host.Should().BeNull();
400+
hostAsserted = true;
401+
402+
return next(invCtx);
403+
})
404+
.Build();
405+
406+
_ = parser.Invoke(string.Empty);
407+
408+
hostAsserted.Should().BeTrue();
409+
}
369410
}
370411
}

src/System.CommandLine.Hosting/HostingExtensions.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,5 +138,12 @@ public static InvocationContext GetInvocationContext(this HostBuilderContext con
138138

139139
throw new InvalidOperationException("Host builder has no Invocation Context registered to it.");
140140
}
141+
142+
public static IHost GetHost(this InvocationContext invocationContext)
143+
{
144+
_ = invocationContext ?? throw new ArgumentNullException(paramName: nameof(invocationContext));
145+
var hostModelBinder = new ModelBinder<IHost>();
146+
return (IHost)hostModelBinder.CreateInstance(invocationContext.BindingContext);
147+
}
141148
}
142149
}

0 commit comments

Comments
 (0)