Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Hosting extensions #2450

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
10 changes: 8 additions & 2 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,15 @@
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="4.0.1" />
<!-- Runtime dependencies -->
<PackageVersion Include="Microsoft.Extensions.Configuration.CommandLine" Version="6.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.CommandLine">
<Version>6.0.0</Version>
<Version Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net8.0'))">8.0.0</Version>
</PackageVersion>
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
<PackageVersion Include="Microsoft.Extensions.Hosting">
<Version>6.0.0</Version>
<Version Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net8.0'))">8.0.0</Version>
</PackageVersion>
<!-- external dependencies -->
<PackageVersion Include="ApprovalTests" Version="7.0.0-beta.3" />
<PackageVersion Include="BenchmarkDotNet" Version="0.13.1" />
Expand Down
150 changes: 150 additions & 0 deletions src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
#if NET8_0_OR_GREATER
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace System.CommandLine.Hosting;

public class HostApplicationBuilderAction() : HostingAction()
{
private new readonly Func<string[], HostApplicationBuilder>? _createHostBuilder;

Check failure on line 11 in src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs

View check run for this annotation

Azure Pipelines / command-line-api (Build and Test MacOS Debug)

src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs#L11

src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs(11,66): error CS0649: (NETCORE_ENGINEERING_TELEMETRY=Build) Field 'HostApplicationBuilderAction._createHostBuilder' is never assigned to, and will always have its default value null

Check failure on line 11 in src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs

View check run for this annotation

Azure Pipelines / command-line-api (Build and Test MacOS Release)

src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs#L11

src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs(11,66): error CS0649: (NETCORE_ENGINEERING_TELEMETRY=Build) Field 'HostApplicationBuilderAction._createHostBuilder' is never assigned to, and will always have its default value null

Check failure on line 11 in src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs

View check run for this annotation

Azure Pipelines / command-line-api (Build and Test Ubuntu Release)

src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs#L11

src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs(11,66): error CS0649: (NETCORE_ENGINEERING_TELEMETRY=Build) Field 'HostApplicationBuilderAction._createHostBuilder' is never assigned to, and will always have its default value null

Check failure on line 11 in src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs

View check run for this annotation

Azure Pipelines / command-line-api (Build and Test Ubuntu Debug)

src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs#L11

src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs(11,66): error CS0649: (NETCORE_ENGINEERING_TELEMETRY=Build) Field 'HostApplicationBuilderAction._createHostBuilder' is never assigned to, and will always have its default value null

Check failure on line 11 in src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs

View check run for this annotation

Azure Pipelines / command-line-api

src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs#L11

src/System.CommandLine.Hosting/HostApplicationBuilderAction.cs(11,66): error CS0649: (NETCORE_ENGINEERING_TELEMETRY=Build) Field 'HostApplicationBuilderAction._createHostBuilder' is never assigned to, and will always have its default value null
public new Action<HostApplicationBuilder>? ConfigureHost { get; set; }

protected override IHostBuilder CreateHostBuiderCore(string[] args)
{
var hostBuilder = _createHostBuilder?.Invoke(args) ??
new HostApplicationBuilder(args);
return new HostApplicationBuilderWrapper(hostBuilder);
}

protected override void ConfigureHostBuilder(IHostBuilder hostBuilder)
{
base.ConfigureHostBuilder(hostBuilder);
ConfigureHost?.Invoke(GetHostApplicationBuilder(hostBuilder));
}

private static HostApplicationBuilder GetHostApplicationBuilder(
IHostBuilder hostBuilder
)
{
return (HostApplicationBuilder)hostBuilder
.Properties[typeof(HostApplicationBuilder)];
}

private class HostApplicationBuilderWrapper(
HostApplicationBuilder hostApplicationBuilder
) : IHostBuilder
{
private Action? _useServiceProviderFactoryAction;
private object? _configureServiceProviderBuilderAction;

public HostBuilderContext Context { get; } = new(
((IHostApplicationBuilder)hostApplicationBuilder).Properties
)
{
Configuration = hostApplicationBuilder.Configuration,
HostingEnvironment = hostApplicationBuilder.Environment,
Properties =
{ { typeof(HostApplicationBuilder), hostApplicationBuilder } }
};

public IDictionary<object, object> Properties =>
((IHostApplicationBuilder)hostApplicationBuilder).Properties;

public IHost Build()
{
_useServiceProviderFactoryAction?.Invoke();
return hostApplicationBuilder.Build();
}

public IHostBuilder ConfigureHostConfiguration(
Action<IConfigurationBuilder> configureDelegate
)
{
configureDelegate?.Invoke(hostApplicationBuilder.Configuration);
return this;
}

public IHostBuilder ConfigureAppConfiguration(
Action<HostBuilderContext, IConfigurationBuilder> configureDelegate
)
{
SynchronizeContext();
configureDelegate?.Invoke(
Context,
hostApplicationBuilder.Configuration
);
SynchronizeContext();
return this;
}

public IHostBuilder ConfigureServices(
Action<HostBuilderContext, IServiceCollection> configureDelegate
)
{
SynchronizeContext();
configureDelegate?.Invoke(Context, hostApplicationBuilder.Services);
SynchronizeContext();
return this;
}

IHostBuilder IHostBuilder.UseServiceProviderFactory<TContainerBuilder>(
IServiceProviderFactory<TContainerBuilder> factory
)
{
_useServiceProviderFactoryAction = () =>
{
Action<TContainerBuilder>? configureDelegate = null;
if (_configureServiceProviderBuilderAction is Action<HostBuilderContext, TContainerBuilder> configureDelegateWithContext)
{
configureDelegate = builder =>
{
SynchronizeContext();
configureDelegateWithContext(Context, builder);
SynchronizeContext();
};
}
hostApplicationBuilder.ConfigureContainer(factory, configureDelegate);
};
return this;
}

IHostBuilder IHostBuilder.UseServiceProviderFactory<TContainerBuilder>(
Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>> factory
)
{
_useServiceProviderFactoryAction = () =>
{
Action<TContainerBuilder>? configureDelegate = null;
if (_configureServiceProviderBuilderAction is Action<HostBuilderContext, TContainerBuilder> configureDelegateWithContext)
{
configureDelegate = builder =>
{
SynchronizeContext();
configureDelegateWithContext(Context, builder);
SynchronizeContext();
};
}
var factoryInstance = factory(Context);
hostApplicationBuilder.ConfigureContainer(factoryInstance, configureDelegate);
};
return this;
}

IHostBuilder IHostBuilder.ConfigureContainer<TContainerBuilder>(
Action<HostBuilderContext, TContainerBuilder> configureDelegate
)
{
_configureServiceProviderBuilderAction = configureDelegate;
return this;
}

private void SynchronizeContext()
{
Context.Configuration = hostApplicationBuilder.Configuration;
Context.HostingEnvironment = hostApplicationBuilder.Environment;
}
}
}
#endif
56 changes: 56 additions & 0 deletions src/System.CommandLine.Hosting/HostConfigurationDirective.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System.Collections.Generic;
using System.Linq;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

using System.CommandLine.Parsing;

namespace System.CommandLine.Hosting;

public class HostConfigurationDirective() : Directive(Name)
{
public new const string Name = "config";

internal static void ConfigureHostBuilder(IHostBuilder hostBuilder)
{
var parseResult = hostBuilder.GetParseResult();
if (parseResult.Configuration.RootCommand is RootCommand rootCommand &&
rootCommand.Directives.FirstOrDefault(IsConfigDirective)
is Directive configDirective &&
parseResult.GetResult(configDirective)
is DirectiveResult configResult
)
{
var configKvps = configResult.Values.Select(GetKeyValuePair)
.ToList();
hostBuilder.ConfigureHostConfiguration(
(config) => config.AddInMemoryCollection(configKvps)
);
}

static bool IsConfigDirective(Directive directive) =>
string.Equals(directive.Name, Name, StringComparison.OrdinalIgnoreCase);

[Diagnostics.CodeAnalysis.SuppressMessage(
"Style",
"IDE0057: Use range operator",
Justification = ".NET Standard 2.0"
)]
static KeyValuePair<string, string?> GetKeyValuePair(string configDirective)
{
ReadOnlySpan<char> kvpSpan = configDirective.AsSpan();
int eqlIdx = kvpSpan.IndexOf('=');
string key;
string? value = default;
if (eqlIdx < 0)
key = kvpSpan.Trim().ToString();
else
{
key = kvpSpan.Slice(0, eqlIdx).Trim().ToString();
value = kvpSpan.Slice(eqlIdx + 1).Trim().ToString();
}
return new KeyValuePair<string, string?>(key, value);
}
}
}
Loading
Loading