You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor WASM PWA发布后出现依赖注入错误

问题描述

我们有一个Blazor WASM PWA独立应用(无同站点后端),用于本地发布测试。使用命令:

dotnet publish "$directorypath\Demo.Web.csproj" -c Release -o $destination

发布过程看似正常,但加载站点时出现以下错误:

blazor.webassembly.js:1 System.AggregateException: AggregateException_ctor_DefaultMessage (TrimmingAnnotationsDoNotMatch_NewConstraint, MyHelper`1, IMyHelper`1)
 ---> System.ArgumentException: TrimmingAnnotationsDoNotMatch_NewConstraint, Helpers.FluentValidationEditContext`1, Helpers.IFluentValidationEditContext`1
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.ValidateTrimmingAnnotations(Type , Type[] , Type , Type[] )
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.Populate()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory..ctor(ICollection`1 )
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 , ServiceProviderOptions )
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection , ServiceProviderOptions )
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection , Boolean )
   at Microsoft.AspNetCore.Components.WebAssembly.Hosting.WebAssemblyHostBuilder.<>c__DisplayClass5_0.<.ctor>b__0()
   at Microsoft.AspNetCore.Components.WebAssembly.Hosting.WebAssemblyHostBuilder.Build()
   at Program.<Main>$(String[] args)
   Exception_EndOfInnerExceptionStack
callEntryPoint @ blazor.webassembly.js:1

该应用在命令行中运行正常,请问此问题的原因是什么?

问题原因
  • 这是Blazor WASM Release发布时默认启用的代码裁剪(Trimming)机制引发的错误。裁剪会移除未被检测到的代码以缩小应用体积,但你的泛型服务实现类FluentValidationEditContext<T>和对应接口IFluentValidationEditContext<T>的裁剪注解不匹配,尤其是泛型约束(比如new()构造约束)的注解不一致。
  • DI容器在构建服务提供器时会验证服务类型的裁剪注解,当实现类和接口的注解无法对齐时,就会抛出TrimmingAnnotationsDoNotMatch_NewConstraint异常。
  • 命令行运行正常是因为Debug模式默认关闭代码裁剪,不会触发这个验证逻辑。

内容的提问来源于stack exchange,提问作者Luis Abreu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 06:53:13