I have a problem with dependecy injection in Azure Functions. I read every guide and any issue here on stackoverflow but I can't found a solution.
I'm working with Visual Studio 2019 and Azurite for testing in my local machine. I tried to make a project without and It works fine. The project is an Azure Functions with HttpTrigger.
Here the link to my github repository
I paste here my Startup's code:
[assembly: FunctionsStartup(typeof(Startup))]
namespace ZanettiClod.SampleAzureFunctions
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient();
builder.Services.AddSingleton<IProductService, ProductService>();
builder.Services.AddSingleton<IProductRepository<Product>, ProductRepository>();
}
}
}
And my Program's code:
namespace ZanettiClod.SampleAzureFunctions
{
public class Program
{
public static void Main()
{
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.Build();
host.Run();
}
}
}
My GetProducts's Code:
namespace ZanettiClod.SampleAzureFunctions
{
public class GetProducts
{
private readonly IProductService _productService;
public GetProducts(IProductService productService)
{
_productService = productService;
}
[Function("GetProducts")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get")]
HttpRequestData req,
FunctionContext executionContext)
{
var logger = executionContext.GetLogger("GetProducts");
logger.LogInformation("C# HTTP trigger function processed a request.");
var products = await _productService.GetAllProducts();
var response = req.CreateResponse(HttpStatusCode.OK);
await response.WriteAsJsonAsync(products);
return response;
}
}
}
And here is the error I get back: screeshot
Thanks in advance for the help
CodePudding user response:
You could make below changes to make it work. I tested for Dependency injection and it worked.
Move dependency injection from startup.cs to program.cs. That's how it works for target framework .Net 5.0. Documentation - https://docs.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide
namespace ZanettiClod.SampleAzureFunctions { public class Program { public static void Main() { var host = new HostBuilder() .ConfigureFunctionsWorkerDefaults() .ConfigureServices(s => { s.AddHttpClient(); s.AddSingleton<IProductService, ProductService>(); s.AddSingleton<IProductRepository<Product>, ProductRepository>(); }) .Build(); host.Run(); } } }
Change the qualifier for _productService from static to readonly in CreateProduct class. Dependency injection doesn't work on static member variables. Also remove static qualifier from your function.
public class CreateProduct { private readonly IProductService _productService; public CreateProduct(IProductService productService) { _productService = productService; } [Function("CreateProduct")] public async Task<HttpResponseData> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req, FunctionContext executionContext) { var logger = executionContext.GetLogger("CreateProduct"); logger.LogInformation("C# HTTP trigger function processed a request."); var product = await req.ReadFromJsonAsync<Product>(); _productService.CreateProduct(product); var response = req.CreateResponse(HttpStatusCode.OK); await response.WriteAsJsonAsync( new { Result = true, Message = $"Name: {product.Name}, Price: {product.Price}" }); return response; } }
}