CodexBloom - Programming Q&A Platform

Difficulty Integrating Dependency Injection with Azure Functions in .NET 6 and Managing Scoped Services

šŸ‘€ Views: 73 šŸ’¬ Answers: 1 šŸ“… Created: 2025-07-05
azure-functions dependency-injection dotnet-6 csharp

I recently switched to I'm currently trying to set up dependency injection for my Azure Functions project using .NET 6. I have a service that I want to be scoped, and I’m working with an scenario where the scoped service is being resolved incorrectly. Here's what I have: ```csharp public class MyFunction { private readonly IMyScopedService _myScopedService; public MyFunction(IMyScopedService myScopedService) { _myScopedService = myScopedService; } [FunctionName("MyFunction")] public async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log) { // Using the scoped service var result = await _myScopedService.GetDataAsync(); return new OkObjectResult(result); } } ``` In my `Startup.cs`, I have the following configuration: ```csharp public class Startup : FunctionsStartup { public override void Configure(IFunctionsHostBuilder builder) { builder.Services.AddScoped<IMyScopedService, MyScopedService>(); } } ``` However, when I deploy and run the function, I get the following behavior: `InvalidOperationException: Unable to resolve service for type 'IMyScopedService' while attempting to activate 'MyFunction'.` This seems to indicate that the service isn't being injected correctly. I've ensured that my `Startup` class is being recognized, and I have the `FunctionsStartup` attribute in place. I've also looked at the Azure Functions documentation but haven't found anything that specifically addresses managing scoped services in this context. I tried changing the service lifetime to singleton temporarily just to see if it would resolve the scenario, and it did, but that's not the behavior I want. Any pointers on how to properly manage scoped services in Azure Functions with .NET 6 would be greatly appreciated! I'm coming from a different tech stack and learning Csharp. Any ideas what could be causing this?