DI in Azure Functions

后端 未结 11 1082
庸人自扰
庸人自扰 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:29

    Actually there is a much nicer and simpler way provided out of the box by Microsoft. It is a bit hard to find though. You simply create a start up class and add all required services here, and then you can use constructor injection like in regular web apps and web apis.

    This is all you need to do.

    First I create my start up class, I call mine Startup.cs to be consistent with Razor web apps, although this is for Azure Functions, but still it's the Microsoft way.

    using System;
    using com.paypal;
    using dk.commentor.bl.command;
    using dk.commentor.logger;
    using dk.commentor.sl;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Hosting;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using org.openerp;
    
    [assembly:Microsoft.Azure.WebJobs.Hosting.WebJobsStartup(typeof(dk.commentor.starterproject.api.Startup))]
    namespace dk.commentor.starterproject.api
    {
    
        public class Startup : IWebJobsStartup
        {
    
            public void Configure(IWebJobsBuilder builder)
            {
                builder.Services.AddSingleton();
                builder.Services.AddSingleton();
                builder.Services.AddSingleton();
                builder.Services.AddSingleton();
                Console.WriteLine("Host started!");
            }
        }
    }
    

    Next I change the method call in the function from static to non-static, and I add a constructor to the class (which is now also non-static). In this constructor I simply add the services I require as constructor parameters.

    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json;
    using dk.commentor.bl.command;
    
    namespace dk.commentor.starterproject.api
    {
        public class ProcessOrder
        {
            private ProcessOrderCommand processOrderCommand;
    
            public ProcessOrder(ProcessOrderCommand processOrderCommand) {
                this.processOrderCommand = processOrderCommand;
            }
    
            [FunctionName("ProcessOrder")]
            public async Task Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log)
            {
                log.LogInformation("C# HTTP trigger ProcessOrder called!");
                log.LogInformation(System.Environment.StackTrace);
    
                string jsonRequestData = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic requestData = JsonConvert.DeserializeObject(jsonRequestData);
    
                if(requestData?.orderId != null)
                    return (ActionResult)new OkObjectResult($"Processing order with id {requestData.orderId}");
                else
                    return new BadRequestObjectResult("Please pass an orderId in the request body");
            }
        }
    }
    

    Hopes this helps.

提交回复
热议问题