Skip to content

Commit

Permalink
stub hosting extensions
Browse files Browse the repository at this point in the history
stub a UseHost extension method to configure app with
an IHost and IHostBuilder

Inject CommandContext as a service
  • Loading branch information
drewburlingame committed May 1, 2021
1 parent 87fbb45 commit 632ff60
Show file tree
Hide file tree
Showing 3 changed files with 153 additions and 0 deletions.
27 changes: 27 additions & 0 deletions CommandDotNet.Hosting/CommandDotNet.Hosting.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<AssemblyTitle>CommandDotNet.Hosting</AssemblyTitle>
<Description>Integrates Microsoft.Extensions.Hosting with CommandDotNet</Description>
</PropertyGroup>
<ItemGroup>
<Compile Remove="output\**" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Remove="output\**" />
</ItemGroup>
<ItemGroup>
<None Remove="output\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.4" />
<PackageReference Include="Nullable" Version="1.2.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CommandDotNet\CommandDotNet.csproj" />
</ItemGroup>

</Project>
116 changes: 116 additions & 0 deletions CommandDotNet.Hosting/HostingExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
using System;
using System.IO;
using System.Threading.Tasks;
using CommandDotNet.Execution;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace CommandDotNet.Hosting
{
public static class HostingExtensions
{
public static AppRunner UseHost(this AppRunner runner,
string[]? args = null,
Action<IHostBuilder>? configureHost = null,
Func<IHostBuilder> hostBuilderFactory = null,
bool supportReplSessions = false)
{
var hostBuilder = hostBuilderFactory?.Invoke() ?? Host.CreateDefaultBuilder(args);

hostBuilder.ConfigureHostConfiguration(hostConfig =>
{
hostConfig.SetBasePath(Directory.GetCurrentDirectory());
});

configureHost?.Invoke(hostBuilder);
return runner.UseHost(hostBuilder, supportReplSessions);
}

public static AppRunner UseHost(this AppRunner runner, IHostBuilder hostBuilder, bool supportReplSessions = false)
{
if (hostBuilder == null)
{
throw new ArgumentNullException(nameof(hostBuilder));
}

return runner.Configure(cfg =>
{
hostBuilder.ConfigureServices(services =>
{
if (supportReplSessions)
{
services.AddScoped<ScopedServices>();
services.AddScoped(p => p.GetRequiredService<ScopedServices>().CommandContext!);
services.AddScoped(p => p.GetRequiredService<ScopedServices>().CommandContext!.Console);
}
else
{
services.AddSingleton<ScopedServices>();
services.AddSingleton(p => p.GetRequiredService<ScopedServices>().CommandContext!);
services.AddSingleton(p => p.GetRequiredService<ScopedServices>().CommandContext!.Console);
}
});

var host = hostBuilder.Build();

cfg.UseMiddleware(RunHost, MiddlewareSteps.CancellationHandler + 1000);
cfg.UseMiddleware(InjectCommandContextForDI, MiddlewareSteps.CancellationHandler + 1001);
cfg.Services.Add(new Config(host, supportReplSessions));
});
}

private static async Task<int> RunHost(CommandContext context, ExecutionDelegate next)
{
var config = context.AppConfig.Services.GetOrThrow<Config>();

if (config.IsStarted)
{
// this call is within a REPL session.
// do not recreate the host
return await next(context);
}

config.IsStarted = true;
await config.Host.StartAsync();
var result = await next(context);
await config.Host.StopAsync();

return result;
}

private class Config
{
public bool IsStarted;
public IHost Host { get; }
public bool SupportReplSessions { get; }

public Config(IHost host, bool supportReplSessions)
{
Host = host ?? throw new ArgumentNullException(nameof(host));
SupportReplSessions = supportReplSessions;
}
}

private class ScopedServices
{
public CommandContext? CommandContext;
}

private static Task<int> InjectCommandContextForDI(CommandContext context, ExecutionDelegate next)
{
var config = context.AppConfig.Services.GetOrThrow<Config>();
var serviceProvider = config.Host.Services;

if (config.SupportReplSessions)
{
using var scope = serviceProvider.CreateScope();
scope.ServiceProvider.GetRequiredService<ScopedServices>().CommandContext = context;
return next(context);
}

serviceProvider.GetRequiredService<ScopedServices>().CommandContext = context;
return next(context);
}
}
}
10 changes: 10 additions & 0 deletions CommandDotNet.sln
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CommandDotNet.Example.Tests
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommandDotNet.DataAnnotations", "CommandDotNet.DataAnnotations\CommandDotNet.DataAnnotations.csproj", "{558AA426-06D4-4FC9-B2E5-B6742F0A5D77}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommandDotNet.Hosting", "CommandDotNet.Hosting\CommandDotNet.Hosting.csproj", "{969B52A2-8790-47C6-A624-AB7FA1383AE7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -94,6 +96,14 @@ Global
{558AA426-06D4-4FC9-B2E5-B6742F0A5D77}.Debug|Any CPU.Build.0 = Debug|Any CPU
{558AA426-06D4-4FC9-B2E5-B6742F0A5D77}.Release|Any CPU.ActiveCfg = Release|Any CPU
{558AA426-06D4-4FC9-B2E5-B6742F0A5D77}.Release|Any CPU.Build.0 = Release|Any CPU
{969B52A2-8790-47C6-A624-AB7FA1383AE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{969B52A2-8790-47C6-A624-AB7FA1383AE7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{969B52A2-8790-47C6-A624-AB7FA1383AE7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{969B52A2-8790-47C6-A624-AB7FA1383AE7}.Release|Any CPU.Build.0 = Release|Any CPU
{1149E03F-FF07-448A-BB42-82876459B138}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1149E03F-FF07-448A-BB42-82876459B138}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1149E03F-FF07-448A-BB42-82876459B138}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1149E03F-FF07-448A-BB42-82876459B138}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down

0 comments on commit 632ff60

Please sign in to comment.