CodexBloom - Programming Q&A Platform

How to implement guide with dependency injection scoping in .net 7 blazor server app - services not resolving properly

👀 Views: 2 💬 Answers: 1 📅 Created: 2025-06-06
blazor dependency-injection dotnet-7 C#

I'm stuck trying to I've looked through the documentation and I'm still confused about I'm working with a puzzling scenario with dependency injection in my .NET 7 Blazor Server application. I have a service that is registered with a scoped lifetime, but it seems like my component is not resolving it correctly. When I try to inject the service, I get an `InvalidOperationException` with the message, "want to resolve scoped service 'MyNamespace.Services.MyScopedService' from root provider." Here's how I've set up the service in my `Startup.cs`: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddScoped<MyScopedService>(); // My scoped service } ``` In my Blazor component, I am trying to inject the service like this: ```csharp @inject MyScopedService MyScopedService ``` I've also ensured that I'm using the Blazor component correctly within the app and that the `MyScopedService` class is a valid service with the necessary constructor dependencies. However, the behavior continues when the component is rendered. I’ve verified that I'm not trying to access the service from a static context or outside of the Blazor lifecycle. Could this be related to how the Blazor lifecycle works, or am I missing something in the configuration? I've tested this with a simple logging service, and it works fine, making me suspect it's something specific to my scoped service implementation. Any insights would be greatly appreciated! How would you solve this? I'm using C# 3.10 in this project. Any examples would be super helpful.