CodexBloom - Programming Q&A Platform

How to implement guide with dependency injection in asp.net core 6: how to to resolve service of type

πŸ‘€ Views: 27 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-03
asp.net-core dependency-injection services csharp

I've tried everything I can think of but I'm currently working on an ASP.NET Core 6 web application, and I'm having trouble with Dependency Injection... I have a service interface `IMyService` and its implementation `MyService`, which I am trying to inject into a controller. However, I keep getting the behavior: `InvalidOperationException: Unable to resolve service for type 'MyNamespace.IMyService' while attempting to activate 'MyNamespace.MyController'.` Here’s what I have in my `Startup.cs` file: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddScoped<IMyService, MyService>(); } ``` In my controller, it looks like this: ```csharp public class MyController : ControllerBase { private readonly IMyService _myService; public MyController(IMyService myService) { _myService = myService; } [HttpGet] public IActionResult Get() { var result = _myService.GetData(); return Ok(result); } } ``` I have made sure that `MyService` implements `IMyService` correctly, like so: ```csharp public class MyService : IMyService { public IEnumerable<string> GetData() { return new List<string> { "data1", "data2" }; } } ``` I’m also certain that no other configurations are overriding the service registrations. I’ve tried cleaning and rebuilding the solution, but the scenario continues. Is there something I might be missing, or a common pitfall with DI in ASP.NET Core 6 that I should be aware of? Any help would be greatly appreciated! For context: I'm using Csharp on Linux. Am I missing something obvious? The stack includes Csharp and several other technologies. Is this even possible? This is my first time working with Csharp 3.11. I'd love to hear your thoughts on this.