Reputation: 1797
I am trying to call a repository class from an Azure function but I am getting an error
There is no argument given that corresponds to the formal parameter
I copied the repository class structure from a .NET Core Web API project and know this has to do with dependency injection.
The constructor of the repository class looks like this:
public CaseRepository(ILogger<CaseRepository> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
How can I pass this into the static method of an Azure Function as I do with the Web API call like this:
[FunctionName("TestFunction")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log, CaseRepository caseRepository)
{
// ...
}
Upvotes: 1
Views: 668
Reputation: 10849
You can define the dependency declaration in the Startup
class as shown in this file and later instead of defining the function as static
define it normal class function. In the class constructor inject the required dependency. See this for reference.
Startup class
[assembly: FunctionsStartup(typeof(YourNamespace.Startup))]
namespace YourNamespace
{
public class Startup : FunctionsStartup
{
builder.Services.AddSingleton<ICaseRepository, CaseRepository>();
}
}
Usage - here ICaseRepository
is injected in the class containing the Azure functions.
public class TestFunction
{
private readonly ICaseRepository caseRepository;
public TestFunction(ICaseRepository caseRepository)
{
this.caseRepository= caseRepository;
}
[FunctionName("TestFunction")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
// ... use caseRepository instance
}
}
Upvotes: 1