最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to invoke AWS Lambda through service layer in .NET API project and deploy via AWS CLI - Stack Overflow

programmeradmin0浏览0评论

I have an ASP.NET Core Web API project and a separate service layer that contains business logic. I want to invoke an AWS Lambda function from my service layer (not directly from the API), and handle the result in my API. Also, I want to package and deploy the Lambda function using AWS CLI and integrate it into my existing CI/CD pipeline.

What I've done:

  1. I added this Lambda function inside my service layer

    using Amazon.Lambda.Core;
    using System;
    using System.Collections.Generic;
    using Amazon.Lambda.Serialization.SystemTextJson;
    
    [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
    
    namespace MyLambdaFunction
    {
        public class MyLambda
        {
            private readonly object cacheLock = new object();
    
            public MyLambda()
            {
                // You can initialize services here if needed
            }
    
            public MyResponse FunctionHandler(DateTime fromDate, DateTime toDate, ILambdaContext context)
            {
                lock (cacheLock)
                {
                    // Logic to get data from cache or service if needed
                    MyResponse result = new MyResponse(); // Replace with actual data retrieval logic
                    return result;
                }
            }
        }
    }
    
  2. Added the following Lambda invocation logic in the service layer of the API project:

    public class LambdaInvokerService
    {
        private readonly IAmazonLambda _lambdaClient;
    
        public LambdaInvokerService(IAmazonLambda lambdaClient)
        {
            _lambdaClient = lambdaClient;
        }
    
        public async Task<string> InvokeLambdaAsync(string functionName, object payload)
        {
            var request = new InvokeRequest
            {
                FunctionName = functionName,
                Payload = System.Text.Json.JsonSerializer.Serialize(payload)
            };
            var response = await _lambdaClient.InvokeAsync(request);
            return new StreamReader(response.Payload).ReadToEnd();
        }
    }
    

Questions:

  1. Is this a correct design for invoking Lambda from the service layer? Any improvements?
  2. How can I deploy the Lambda function using AWS CLI, and how does it know which function to deploy (via .NET lambda package)?
  3. How can I integrate Lambda deployment into my existing CI/CD pipeline automatically?
发布评论

评论列表(0)

  1. 暂无评论