Skip to content

Commit

Permalink
Use custom service provider with static NavManager for static rendere…
Browse files Browse the repository at this point in the history
…d components
  • Loading branch information
mythz committed Mar 24, 2024
1 parent ed6c4c9 commit 90e9516
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
29 changes: 27 additions & 2 deletions MyApp/Configure.Renderer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Data;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using MyApp.Components.Shared;
using MyApp.Data;
Expand All @@ -15,17 +16,41 @@ namespace MyApp;

public class ConfigureRenderer : IHostingStartup
{
static T RequiredService<T>() where T : notnull =>
ServiceStackHost.Instance.GetApplicationServices().GetRequiredService<T>();

public void Configure(IWebHostBuilder builder) => builder
.ConfigureServices(services =>
.ConfigureServices((context,services) =>
{
services.AddScoped<HtmlRenderer>();
var svc = new ServiceCollection();
svc.AddLogging();
svc.AddSingleton<AppConfig>(c => RequiredService<AppConfig>());
svc.AddSingleton<MarkdownQuestions>(c => RequiredService<MarkdownQuestions>());
svc.AddSingleton<NavigationManager>(c => new StaticNavigationManager());
var sp = svc.BuildServiceProvider();
services.AddScoped<HtmlRenderer>(c => new HtmlRenderer(sp, c.GetRequiredService<ILoggerFactory>()));
services.AddScoped<BlazorRenderer>();
services.AddSingleton<RendererCache>();
services.RegisterService<RenderServices>();
})
.ConfigureAppHost(appHost => { });
}

// Use fake NavigationManager in Static Rendering to avoid NavigationManager has not been initialized Exception
internal class StaticNavigationManager : NavigationManager
{
public StaticNavigationManager()
{
Initialize("https://pvq.app/", "https://pvq.app/");
}

protected override void NavigateToCore(string uri, bool forceLoad)
{
NotifyLocationChanged(false);
}
}

public class RendererCache(AppConfig appConfig, R2VirtualFiles r2)
{
private static bool DisableCache = false;
Expand Down
2 changes: 1 addition & 1 deletion MyApp/Markdown.Questions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace MyApp;

public class MarkdownQuestions(ILogger<MarkdownPages> log, IWebHostEnvironment env, IVirtualFiles fs)
public class MarkdownQuestions(ILogger<MarkdownQuestions> log, IWebHostEnvironment env, IVirtualFiles fs)
: MarkdownPagesBase<MarkdownFileInfo>(log, env, fs)
{
public override string Id => "questions";
Expand Down

0 comments on commit 90e9516

Please sign in to comment.