.NET 9.0 Blazor Web应用重建后错误持续存在(仅无痕模式正常)的问题求助
.NET 9.0 Blazor Web应用重建后错误持续存在(仅无痕模式正常)的问题求助
各位好,我最近在Visual Studio里用.NET 9.0的Blazor Web App模板做依赖注入的实验,想搞明白Blazor里DI的工作逻辑,结果遇到了一个让我摸不着头脑的问题,希望大家能给点思路。
最开始我搭了个简单的DI场景是正常运行的,但后来改代码引入了bug,当我想回滚到之前的正确代码时,怪事发生了——原本正常的代码居然不工作了!只有在浏览器的无痕模式下打开应用,代码才能恢复正常。我已经尝试过清理解决方案、重新构建,但问题依旧,这让我开始怀疑:是不是有什么我没注意到的缓存或者残留资源,导致浏览器跑的不是我当前的代码版本?
先给大家说下我的代码背景(核心逻辑很简单,和模板里的Counter页面相关):
- 我在WebClient.App项目里创建了
ICountService接口,定义了获取步长的方法 - 实现了
VariableCountService:构造函数接收一个整数作为步长 - 又做了
SingleStepCountService,继承自VariableCountService,默认步长设为1 - 把Counter页面改成注入这个服务,用服务的步长来计数
下面是我的核心代码:
修改后的Counter.razor
@page "/counter" @rendermode InteractiveWebAssembly @inject ICountService CountService <PageTitle>Counter</PageTitle> <h1>Counter</h1> <p role="status">Current count: @currentCount</p> <button class="btn btn-primary" @onclick="IncrementCount">Click me</button> @code { private int currentCount = 0; private void IncrementCount() { Console.WriteLine("Incrementing counter with count service..."); currentCount = currentCount + CountService.GetStep(); } }
服务接口与实现类
public interface ICountService { int GetStep(); } public class VariableCountService : ICountService { protected int StepSize { get; set; } public VariableCountService(int stepSize) { StepSize = stepSize; } public int GetStep() { return StepSize; } public override string ToString() { return $"Variable Counter [{StepSize}]"; } } public class SingleStepCountService : VariableCountService { public SingleStepCountService() : base(1) { } public override string ToString() { return "Single Step Counter"; } }
Program.cs里的DI注册
public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorComponents() .AddInteractiveServerComponents() .AddInteractiveWebAssemblyComponents(); // ✅ 最开始这个注册方式完全正常 builder.Services.AddScoped<ICountService, SingleStepCountService>(); // ❌ 我后来尝试的几种VariableCountService注册方式都不行 // builder.Services.AddSingleton<ICountService>(new VariableCountService(2)); // var counter = new VariableCountService(2); // builder.Services.AddSingleton<ICountService>(counter); // var counter = new VariableCountService(2); // builder.Services.AddSingleton<ICountService, VariableCountService>((x) => { return counter; }); var app = builder.Build(); // 省略中间的app配置、管道代码 app.Run(); } }
现在的问题是:当我回滚到那个原本正常的AddScoped<ICountService, SingleStepCountService>()注册方式后,普通浏览器窗口打开应用还是有问题,但无痕模式就完全正常。我已经清理了解决方案的bin/obj目录,也重启过Visual Studio和浏览器,但都没用。
有没有朋友遇到过类似的情况?会不会是浏览器缓存了旧的WebAssembly包?或者Blazor有什么内置的缓存机制我没处理好?麻烦大家给点排查方向,谢谢了!
内容来源于stack exchange
相关产品推荐
相关产品推荐

