DI in Azure Functions

后端 未结 11 1096
庸人自扰
庸人自扰 2020-12-25 10:43

I have some class libraries that I use in my ASP.NET Web API app that handle all my backend stuff e.g. CRUD operations to multiple databases like Azure SQL Database, Cosmos

11条回答
  •  无人及你
    2020-12-25 11:36

    Support for Dependency injection begins with Azure Functions 2.x which means Dependency Injection in Azure function can now leverage .NET Core Dependency Injection features.

    Before you can use dependency injection, you must install the following NuGet packages:

    • Microsoft.Azure.Functions.Extensions
    • Microsoft.NET.Sdk.Functions

    Having Dependency Injection eases things like DBContext, Http client usage (Httpclienfactory), Iloggerfactory, cache support etc.

    Firstly, update the Startup class as shown below

    namespace DemoApp
    {
        public class Startup: FunctionsStartup
        {
            public override void Configure(IFunctionsHostBuilder builder)
            {
                builder.Services.AddScoped();
    
                // Registering Serilog provider
                var logger = new LoggerConfiguration()
                    .WriteTo.Console()
                    .CreateLogger();
                builder.Services.AddLogging(lb => lb.AddSerilog(logger));
                //Reading configuration section can be added here etc.
            }
        }
    }
    

    Secondly, Removal of Static keyword in Function class and method level

    public class DemoFunction
    {
        private readonly IHelloWorld _helloWorld;
        public DemoFunction(IHelloWorld helloWorld)
        {
            _helloWorld = helloWorld;
        }
    
        [FunctionName("HttpDemoFunction")]
        public async Task Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
        }
    

    If we look into above e.g. IHelloWorld is injected using .NET Core DI

    **Note:**In-spite of having latest version of Azure function v3 for Dependency Injection to enable few steps are manual as shown above

    Sample code on github can be found here

提交回复
热议问题