CodexBloom - Programming Q&A Platform

C# 10 - implementing Dependency Injection and Scoped Services in Blazor Server App

πŸ‘€ Views: 2 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-06
c# blazor dependency-injection C#

I'm writing unit tests and I've been researching this but I'm attempting to set up I'm working through a tutorial and I'm working with a question with dependency injection in my Blazor Server application... I have a service that is registered as a scoped service, but I'm experiencing an 'InvalidOperationException' stating that the service want to be resolved because it is not available. This happens when I try to inject this service into a component that gets instantiated dynamically. Here’s how I registered the service: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddScoped<IMyService, MyService>(); } ``` In my component, I'm trying to inject it like this: ```razor @inject IMyService MyService ``` The component is rendered within a `DynamicComponent`, and I suspect this might be the cause of the scenario. When accessing `MyService`, I get the following behavior: `InvalidOperationException: Unable to resolve service for type 'IMyService' while attempting to activate 'MyComponent'`. I’ve tried changing the service registration to singleton, but that leads to issues with state management. Is there a way to correctly inject scoped services into dynamically created components in a Blazor Server application? Any guidance or examples would be greatly appreciated! What are your experiences with this? I'm working on a web app that needs to handle this. I'd love to hear your thoughts on this. I'm working on a microservice that needs to handle this. Has anyone dealt with something similar? This is for a application running on Debian. This is part of a larger REST API I'm building.