Skip to content

Commit

Permalink
feat: Switch NetRunner from IHostBuilder to WebApplicationBuilder
Browse files Browse the repository at this point in the history
- Updated the version of `DotNet.ReproducibleBuilds` package in `Directory.Build.props`
- Added new files to `.gitignore`, `LICENSE`, and `README.md` in `.github/workflows`
- Modified code in `Program.cs` to switch from using `IHostBuilder` to `WebApplicationBuilder`
- Refactored code in `Startup.cs` to use static methods instead of an instance class
- Updated package references in the project file (`YumeChan.NetRunner.csproj`)
- Modified configuration files (`appsettings.Development.json` and `appsettings.json`) for logging with Serilog
  • Loading branch information
SakuraIsayeki committed Sep 21, 2024
1 parent f049257 commit 1255869
Show file tree
Hide file tree
Showing 8 changed files with 111 additions and 77 deletions.
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
</ItemGroup>

<ItemGroup Condition="$(PackAsTool) != 'true'">
<PackageReference Include="DotNet.ReproducibleBuilds" Version="1.2.4" PrivateAssets="All"/>
<PackageReference Include="DotNet.ReproducibleBuilds" Version="1.2.25" PrivateAssets="All"/>
</ItemGroup>
</Project>
3 changes: 3 additions & 0 deletions YumeChan.sln
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
.gitignore = .gitignore
LICENSE = LICENSE
README.md = README.md
G:\YumeChan\.gitmodules = G:\YumeChan\.gitmodules
G:\YumeChan\Directory.Build.props = G:\YumeChan\Directory.Build.props
G:\YumeChan\version.json = G:\YumeChan\version.json
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github/workflows", ".github/workflows", "{24C84DC3-4061-4ACA-88BA-19BDAABB9A15}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="8.0.0-rc.1.23421.29" />
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="8.0.8" />
<PackageReference Include="Nodsoft.MoltenObsidian.Blazor" Version="1.1.1" />
<PackageReference Include="Nodsoft.MoltenObsidian.Vaults.FileSystem" Version="1.1.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.7.3" />
</ItemGroup>

</Project>
34 changes: 18 additions & 16 deletions src/YumeChan.NetRunner/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using DryIoc;
using DryIoc.Microsoft.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
Expand All @@ -11,34 +12,35 @@ namespace YumeChan.NetRunner;

public static class Program
{
private static Container _container = new();
private static readonly LoggerConfiguration _loggerConfiguration = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console();

public static async Task Main(string[] args)
{
Log.Logger = _loggerConfiguration.CreateLogger();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console(applyThemeToRedirectedOutput: true)
.CreateBootstrapLogger();

using IHost host = CreateHostBuilder(args).Build();
IServiceProvider services = host.Services;
WebApplicationBuilder builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });

builder.Host.ConfigureHost();

builder.ConfigureServices();
await using WebApplication host = builder.Build();

YumeCore yumeCore = services.GetRequiredService<YumeCore>();
host.UseApplicationPipeline();

YumeCore yumeCore = host.Services.GetRequiredService<YumeCore>();

await Task.WhenAll(
yumeCore.StartBotAsync(),
host.RunAsync()
);
}
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)

private static void ConfigureHost(this ConfigureHostBuilder builder) => builder
.UseServiceProviderFactory(new DryIocServiceProviderFactory())
.ConfigureLogging(x => x.ClearProviders())
.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>())
.ConfigureContainer<Container>((_, container) => container
.WithDependencyInjectionAdapter()
)
;
);
}
81 changes: 36 additions & 45 deletions src/YumeChan.NetRunner/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,40 +22,38 @@

namespace YumeChan.NetRunner;

public sealed class Startup
public static class Startup
{
public IConfiguration Configuration { get; }

public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
public static WebApplicationBuilder ConfigureServices(this WebApplicationBuilder builder)
{
services.AddYumeCoreServices();
builder.Services.AddYumeCoreServices();

builder.Services.AddSerilog(static (services, lc) => lc
.ReadFrom.Configuration(services.GetRequiredService<IConfiguration>())
.ReadFrom.Services(services)
);

string informationalVersion = Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
services.AddSingleton(new NetRunnerContext(RunnerType.Console, typeof(Program).Assembly.GetName().Name, informationalVersion));
builder.Services.AddSingleton(new NetRunnerContext(RunnerType.Console, typeof(Program).Assembly.GetName().Name, informationalVersion));

services.AddControllers(builder =>
builder.Services.AddControllers(options =>
{
builder.ConfigurePluginNameRoutingToken();
builder.Conventions.Add(new PluginApiRoutingConvention());
options.ConfigurePluginNameRoutingToken();
options.Conventions.Add(new PluginApiRoutingConvention());
}
);

services.AddApiPluginSupport();
services.AddApiPluginsSwagger();
services.AddPluginDocsSupport();
builder.Services.AddApiPluginSupport();
builder.Services.AddApiPluginsSwagger();
builder.Services.AddPluginDocsSupport();

services.AddRazorPages();
services.AddServerSideBlazor();
services.AddHttpContextAccessor();
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddHttpContextAccessor();

services.AddAuthentication(options =>
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = DiscordAuthenticationDefaults.AuthenticationScheme;
Expand All @@ -66,7 +64,7 @@ public void ConfigureServices(IServiceCollection services)
})
.AddDiscord(options =>
{
Configuration.GetSection("DiscordAuth").Bind(options);
builder.Configuration.GetSection("DiscordAuth").Bind(options);

// options.ClientId = Configuration["DiscordAuth:ClientId"];
// options.ClientSecret = Configuration["DiscordAuth:ClientSecret"];
Expand All @@ -78,20 +76,16 @@ public void ConfigureServices(IServiceCollection services)
options.CorrelationCookie.SameSite = SameSiteMode.Lax;
});

services.AddLogging(x =>
{
x.ClearProviders();
x.AddSerilog();
});

services.AddSingleton<IComponentActivator, ComponentActivator>();
services.AddScoped<IClaimsTransformation, WebAppClaims>();
builder.Services.AddSingleton<IComponentActivator, ComponentActivator>();
builder.Services.AddScoped<IClaimsTransformation, WebAppClaims>();

return builder;
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
public static void UseApplicationPipeline(this WebApplication app)
{
if (env.IsDevelopment())
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
Expand All @@ -109,15 +103,15 @@ public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
app.UseStaticFiles();
app.UseStaticFiles(options: new()
{
FileProvider = new PluginWebAssetsProvider(app.ApplicationServices.GetService<ICoreProperties>()?.Path_Plugins
FileProvider = new PluginWebAssetsProvider(app.Services.GetService<ICoreProperties>()?.Path_Plugins
?? throw new InvalidOperationException("Plugin path not found")),

RequestPath = "/_content"
});

app.UseStaticFiles(options: new()
{
FileProvider = new PluginWebAssetsProvider(app.ApplicationServices.GetService<ICoreProperties>()?.Path_Plugins
FileProvider = new PluginWebAssetsProvider(app.Services.GetService<ICoreProperties>()?.Path_Plugins
?? throw new InvalidOperationException("Plugin path not found")),

RequestPath = "/p"
Expand All @@ -131,18 +125,15 @@ public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
app.MapControllers();
app.MapBlazorHub();

app.MapFallback("/api/{*path}", context =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();

endpoints.MapFallback("/api/{*path}", context =>
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
return Task.CompletedTask;
});

endpoints.MapFallbackToPage("/_Host");
context.Response.StatusCode = StatusCodes.Status404NotFound;
return Task.CompletedTask;
});

app.MapFallbackToPage("/_Host");
}
}
2 changes: 1 addition & 1 deletion src/YumeChan.NetRunner/YumeChan.NetRunner.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
<PackageReference Include="Microsoft.TypeScript.MSBuild" Version="5.5.3">
<PackageReference Include="Microsoft.TypeScript.MSBuild" Version="5.6.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
31 changes: 25 additions & 6 deletions src/YumeChan.NetRunner/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,29 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft.AspNetCore": "Warning",
"Microsoft.AspNetCore.Hosting": "Information",
"Microsoft.AspNetCore.Hosting.Diagnostics": "Warning",
"Microsoft.EntityFrameworkCore": "Warning"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u4}] {Message:lj} <s:{SourceContext}> <p:{Properties:j}> {NewLine}{Exception}",
"applyThemeToRedirectOutput": true
}
}
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId"
]
},

"DiscordAuth": {
Expand Down
31 changes: 25 additions & 6 deletions src/YumeChan.NetRunner/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,32 @@
"AllowedHosts": "*",

"DetailedErrors": true,
"Logging": {
"LogLevel": {

"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
"Override": {
"Microsoft.AspNetCore": "Warning",
"Microsoft.AspNetCore.Hosting": "Information",
"Microsoft.AspNetCore.Hosting.Diagnostics": "Warning",
"Microsoft.EntityFrameworkCore": "Warning"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u4}] {Message:lj}{NewLine}{Exception}",
"applyThemeToRedirectOutput": true
}
}
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId"
]
},

"DiscordAuth": {
Expand Down

0 comments on commit 1255869

Please sign in to comment.