In this post let's see how we can use Dependency Injection in Azure Functions.
It's actually quite simple, if you are familiar with .NET Core Dependency
Injection approach, it follows the same pattern.
You just need to create a class that inherits from the abstract FunctionsStartup class (found in Microsoft.Azure.Functions.Extensions
assembly) class and override its Configure method to configure the IoC
container.
Now let's see that in action. I have created a HttpTrigger Azure Function
App using the default Visual Studio template. There I have installed Microsoft.Azure.Functions.Extensions NuGet package.
Then I have added the below Startup class.
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(FunctionApp1.Startup))]
namespace FunctionApp1
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
// TODO: Register Services
}
}
}
Here you need to specify the FunctionsStartup assembly attribute to
specify what's going to be the type to be used as the Startup.
Next is pretty much simple. You can register either Transient, Scoped or
Singleton Services. As you already know, for transient, new service is created
whenever it's requested, for Scoped, one service is created for the lifetime of the
function execution and for Singleton, only one instance is created for the entire lifetime of the
host.
builder.Services.AddTransient<IMyInterface1, MyService1>();
builder.Services.AddScoped<IMyInterface2, MyService2>();
builder.Services.AddSingleton<IMyInterface3, MyService3>();
Alternatively, you can use TryAdd counterparts of above which is
available in the namespace
Microsoft.Extensions.DependencyInjection.Extensions.
And then you can just inject the services in the constructor of the
function class as below.
public class Function1
{
private readonly IMyInterface _myInterface;
public Function1(IMyInterface myInterface)
{
_myInterface = myInterface;
}
[FunctionName("Function1")]
public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
// TODO: Use _myInterface
return new OkResult();
}
}
Hope this helps!
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment