Skip to content

Commit

Permalink
feat(app): hook into host build event via custom di factory
Browse files Browse the repository at this point in the history
  • Loading branch information
SonicGD committed Dec 6, 2023
1 parent 83da572 commit beac6af
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 26 deletions.
8 changes: 3 additions & 5 deletions src/Sitko.Core.App/HostedLifecycleService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,16 @@ internal class HostedLifecycleService : IHostedLifecycleService
private readonly ILogger<HostedLifecycleService> logger;
private readonly IApplicationContext applicationContext;
private readonly IServiceProvider serviceProvider;
private readonly SerilogConfigurator serilogConfigurator;


private readonly IReadOnlyList<ApplicationModuleRegistration> enabledModules;

public HostedLifecycleService(ILogger<HostedLifecycleService> logger, IApplicationContext applicationContext,
IServiceProvider serviceProvider, IEnumerable<ApplicationModuleRegistration> applicationModuleRegistrations,
SerilogConfigurator serilogConfigurator)
IServiceProvider serviceProvider, IEnumerable<ApplicationModuleRegistration> applicationModuleRegistrations)
{
this.logger = logger;
this.applicationContext = applicationContext;
this.serviceProvider = serviceProvider;
this.serilogConfigurator = serilogConfigurator;
enabledModules =
ModulesHelper.GetEnabledModuleRegistrations(applicationContext, applicationModuleRegistrations);
}
Expand All @@ -34,7 +32,7 @@ public HostedLifecycleService(ILogger<HostedLifecycleService> logger, IApplicati
public async Task StartingAsync(CancellationToken cancellationToken)
{
await using var scope = serviceProvider.CreateAsyncScope();
serilogConfigurator.ApplyLogging(applicationContext, enabledModules);

foreach (var enabledModule in enabledModules)
{
var shouldContinue = await enabledModule.GetInstance()
Expand Down
49 changes: 32 additions & 17 deletions src/Sitko.Core.App/SitkoCoreBaseApplicationBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,29 +31,15 @@ protected SitkoCoreBaseApplicationBuilder(string[] args, IServiceCollection serv

// configure logging
Configuration.Add(new SerilogDynamicConfigurationSource());
var tmpLoggerConfiguration = new LoggerConfiguration();
tmpLoggerConfiguration = ConfigureDefautLogger(tmpLoggerConfiguration);
if (BootApplicationContext.Options.EnableConsoleLogging != true)
{
tmpLoggerConfiguration = tmpLoggerConfiguration.WriteTo.Console(
outputTemplate: ApplicationOptions.BaseConsoleLogFormat,
formatProvider: CultureInfo.InvariantCulture,
restrictedToMinimumLevel: LogEventLevel.Debug);
}

var tmpLogger = tmpLoggerConfiguration.CreateLogger();
Log.Logger = tmpLogger; // set default logger until host is started
Console.OutputEncoding = Encoding.UTF8;
InternalLogger = new SerilogLoggerFactory(tmpLogger)
.CreateLogger<ISitkoCoreApplicationBuilder>();
AddModule<CommandsModule>();
InternalLogger = CreateInternalLogger();
Logging.ClearProviders();
Logging.AddSerilog();
serilogConfigurator.Configure(ConfigureDefautLogger);

AddModule<CommandsModule>();

Services.AddSingleton<IApplicationArgsProvider>(argsProvider);
Services.AddSingleton(environment);
Services.AddSingleton(serilogConfigurator);
Services.AddSingleton<IApplicationContext, BuilderApplicationContext>();
Services.AddTransient<IScheduler, Scheduler>();
Services.AddFluentValidationExtensions();
Expand Down Expand Up @@ -117,6 +103,25 @@ public ISitkoCoreApplicationBuilder AddModule<TModule, TModuleOptions>(
public bool HasModule<TModule>() where TModule : IApplicationModule =>
moduleRegistrations.Any(r => r.Type == typeof(TModule));

private ILogger<ISitkoCoreApplicationBuilder> CreateInternalLogger()
{
var tmpLoggerConfiguration = new LoggerConfiguration();
tmpLoggerConfiguration = ConfigureDefautLogger(tmpLoggerConfiguration);
if (BootApplicationContext.Options.EnableConsoleLogging != true)
{
tmpLoggerConfiguration = tmpLoggerConfiguration.WriteTo.Console(
outputTemplate: ApplicationOptions.BaseConsoleLogFormat,
formatProvider: CultureInfo.InvariantCulture,
restrictedToMinimumLevel: LogEventLevel.Debug);
}

var tmpLogger = tmpLoggerConfiguration.CreateLogger();
Log.Logger = tmpLogger; // set default logger until host is started
Console.OutputEncoding = Encoding.UTF8;
return new SerilogLoggerFactory(tmpLogger)
.CreateLogger<ISitkoCoreApplicationBuilder>();
}

private void RegisterModule<TModule, TModuleOptions>(
Action<IApplicationContext, TModuleOptions>? configureOptions = null,
string? optionsKey = null)
Expand Down Expand Up @@ -176,5 +181,15 @@ protected virtual LoggerConfiguration ConfigureDefautLogger(LoggerConfiguration
return loggerConfiguration;
}

protected virtual void BeforeContainerBuild()
{
var enabledModules = ModulesHelper.GetEnabledModuleRegistrations(BootApplicationContext, moduleRegistrations);
serilogConfigurator.ApplyLogging(BootApplicationContext, enabledModules);
foreach (var moduleRegistration in enabledModules)
{
moduleRegistration.PostConfigureServices(BootApplicationContext, Services);
}
}

protected void LogInternal(string message) => InternalLogger.LogInformation("Check log: {Message}", message);
}
30 changes: 27 additions & 3 deletions src/Sitko.Core.App/SitkoCoreServerApplicationBuilder.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Sitko.Core.App;

Expand All @@ -7,9 +8,15 @@ public class SitkoCoreServerApplicationBuilder : SitkoCoreBaseApplicationBuilder
private readonly IHostApplicationBuilder applicationBuilder;

public SitkoCoreServerApplicationBuilder(IHostApplicationBuilder applicationBuilder, string[] args) : base(args,
applicationBuilder.Services, applicationBuilder.Configuration, new ServerApplicationEnvironment(applicationBuilder.Environment),
applicationBuilder.Logging) =>
applicationBuilder.Services, applicationBuilder.Configuration,
new ServerApplicationEnvironment(applicationBuilder.Environment),
applicationBuilder.Logging)
{
this.applicationBuilder = applicationBuilder;
applicationBuilder.ConfigureContainer(new SitkoCoreServiceProviderBuilderFactory(),
_ => BeforeContainerBuild());
}


protected override void BeforeModuleRegistration<TModule, TModuleOptions>(IApplicationContext applicationContext,
ApplicationModuleRegistration moduleRegistration)
Expand All @@ -35,3 +42,20 @@ protected override void AfterModuleRegistration<TModule, TModuleOptions>(IApplic
}
}
}

public class SitkoCoreServiceProviderBuilderFactory : IServiceProviderFactory<SitkoCoreServiceProviderBuilder>
{
public SitkoCoreServiceProviderBuilder CreateBuilder(IServiceCollection services) => new(services);

public IServiceProvider CreateServiceProvider(SitkoCoreServiceProviderBuilder containerBuilder) =>
containerBuilder.Build();
}

public class SitkoCoreServiceProviderBuilder
{
private readonly IServiceCollection services;

public SitkoCoreServiceProviderBuilder(IServiceCollection services) => this.services = services;

public IServiceProvider Build() => services.BuildServiceProvider();
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public SitkoCoreBlazorWasmApplicationBuilder(WebAssemblyHostBuilder builder, str
{
options.AddDefaultResource(typeof(BaseForm));
});
builder.ConfigureContainer(new SitkoCoreServiceProviderBuilderFactory(), _ => BeforeContainerBuild());
}

protected override LoggerConfiguration ConfigureDefautLogger(LoggerConfiguration loggerConfiguration)
Expand All @@ -56,7 +57,8 @@ public static class WebAssemblyHostBuilderExtensions
public static ISitkoCoreBlazorApplicationBuilder AddSitkoCoreBlazorWasm(this WebAssemblyHostBuilder builder) =>
builder.AddSitkoCoreBlazorWasm(Array.Empty<string>());

public static ISitkoCoreBlazorApplicationBuilder AddSitkoCoreBlazorWasm(this WebAssemblyHostBuilder builder, string[] args) =>
public static ISitkoCoreBlazorApplicationBuilder AddSitkoCoreBlazorWasm(this WebAssemblyHostBuilder builder,
string[] args) =>
ApplicationBuilderFactory.GetOrCreateApplicationBuilder(builder,
applicationBuilder => new SitkoCoreBlazorWasmApplicationBuilder(applicationBuilder, args));
}

0 comments on commit beac6af

Please sign in to comment.