1 | initial version |
Dependency Injection (DI) can be employed in Azure Function .NET 6 using the following steps:
Microsoft.Azure.Functions.Extensions.DependencyInjection
Define an interface for the class that you want to inject dependencies into. For example:
public interface IMyService
{
void DoSomething();
}
public class MyService : IMyService
{
public void DoSomething()
{
// implementation
}
}
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddSingleton<IMyService, MyService>();
}
}
public class MyFunction
{
private readonly IMyService _myService;
public MyFunction(IMyService myService)
{
_myService = myService;
}
[FunctionName("MyFunction")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
// use _myService in your function logic
_myService.DoSomething();
return new OkObjectResult("Done!");
}
}