Blazor WebAssembly添加服务时出现依赖注入异常求助
问题分析与解决方案
问题根源
你在Program.cs中仅注册了接口AuthenticationStateProvider到实现类CustomAuthenticationStateProvider的映射,但在MainLayout中直接注入了具体类型CustomAuthenticationStateProvider。DI容器中没有单独注册该具体类型,因此无法找到对应的服务实例。
解决方法一:同时注册具体类型与接口映射
修改Program.cs中的服务注册代码,先注册CustomAuthenticationStateProvider本身,再将其关联到AuthenticationStateProvider接口:
// 先注册具体类型 builder.Services.AddScoped<CustomAuthenticationStateProvider>(); // 再将接口指向已注册的具体类型实例 builder.Services.AddScoped<AuthenticationStateProvider>(sp => sp.GetRequiredService<CustomAuthenticationStateProvider>());
这样DI容器既可以通过接口提供服务(满足Blazor授权系统的需求),也可以直接提供CustomAuthenticationStateProvider实例供你注入使用。
解决方法二:修改注入类型为接口,再转换为具体类
如果不想调整服务注册,可以在MainLayout中先注入AuthenticationStateProvider接口,再转换为你的自定义实现类:
[Inject] private AuthenticationStateProvider AuthStateProvider { get; set; } // 封装成自定义类型的属性,方便调用LoginAsync/LogoutAsync等方法 private CustomAuthenticationStateProvider AuthenticationProvider => (CustomAuthenticationStateProvider)AuthStateProvider;
这种方式遵循面向接口的依赖原则,同时能正常使用自定义实现中的扩展方法。
内容的提问来源于stack exchange,提问作者Nikita Gelfman
相关产品推荐
相关产品推荐

