【问题标题】:Dependency Injection in AWS Lambda function ( .Net Core 2.2 )AWS Lambda 函数中的依赖注入 (.Net Core 2.2)
【发布时间】:2019-10-17 08:57:02
【问题描述】:

我正在尝试使用 .Net Core 2.2 使用以下方法创建 AWS lambda 函数

https://aws.amazon.com/blogs/developer/announcing-amazon-lambda-runtimesupport/

我需要实现依赖注入来注入 DBContxt,业务层的接口也是如此。

由于 appraoch 建议在此类中仅使用静态方法作为 lambda 函数,因此我的构造函数注入似乎不起作用,因为唯一执行的方法是 lambda 函数,我尝试创建静态构造函数和静态初始化程序,但这些都是也没有执行。

以下是示例代码

using Amazon.Lambda.Core;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;

namespace Lambda
{
    public class DoSomething
    {
        // Configuration Service
        public static IConfigurationService ConfigService { get; set; }
        public static IManager Manager { get; set; }

        public static DoSomething()
        {
            Console.WriteLine("Static initializer begin....");
            // Set up Dependency Injection
            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);
            var serviceProvider = serviceCollection.BuildServiceProvider();

            // Get Configuration Service from DI system
            ConfigService = serviceProvider.GetService<IConfigurationService>();
            Console.WriteLine("Static initializer done....");
        }
        // Use this ctor from unit tests that can mock IConfigurationService
        public DoSomething(IConfigurationService configService, IManager Manager)
        {
            Console.WriteLine("Constructor being....");
            ConfigService = configService;
            Manager = Manager;
            Console.WriteLine("Constructor done....");
        }
        /// <summary>
        /// The main entry point for the custom runtime.
        /// </summary>
        /// <param name="args"></param>
        private static async Task Main(string[] args)
        {
            Func<ILambdaContext, string> func = Expire;
            using(var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer()))
            using(var bootstrap = new LambdaBootstrap(handlerWrapper))
            {
                Console.WriteLine("Main done 0....");
                await bootstrap.RunAsync();
            }
            Console.WriteLine("Main done....");
        }

        /// <summary>
        /// Lambda function to expire items.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string Expire(ILambdaContext context)
        {
            Console.WriteLine("Expire called....");
            // Get config setting using input as a key
            var temp = Manager.Expire();
            context.Logger.LogLine($"Processing-3 ..... {temp}");
            return temp;
        }

        static void ConfigureServices(IServiceCollection serviceCollection)
        {
            // PostgreSQL Configuration.
            serviceCollection.AddEntityFrameworkNpgsql().AddDbContext<DbContext>(opt =>
                opt.UseNpgsql(ConfigService.GetConfiguration().GetConnectionString("DbConnection"))
                );

            // Register services with DI system
            serviceCollection.AddTransient<IEnvironmentService, EnvironmentService>();
            serviceCollection.AddTransient<IConfigurationService, ConfigurationService>();
            serviceCollection.AddTransient<IRepository, Repository>();
            serviceCollection.AddTransient<IManager, Manager>();
        }
    }
}

【问题讨论】:

    标签: amazon-web-services aws-lambda


    【解决方案1】:

    我能够使用提到的 AWS 教程和 Tony Sneed 的教程 https://blog.tonysneed.com/2018/12/16/add-net-core-di-and-config-goodness-to-aws-lambda-functions/ 让 DI 运行,但是从 Main 方法调用 DI 初始化,因为它需要是静态的。

    public class Function
    {
        private static IConfigurationService _configService;
        private static IServiceProvider _serviceProvider;
    
        private static async Task Main(string[] args)
        {
            // Setup DI
            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);
            _serviceProvider = serviceCollection.BuildServiceProvider();
    
            // Get Configuration Service from DI
            _configService = _serviceProvider.GetService<IConfigurationService>();
    
            // Setup Lambda
            Func<string, ILambdaContext, string> func = FunctionHandler;
            using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer()))
            using (var bootstrap = new LambdaBootstrap(handlerWrapper))
            {
                await bootstrap.RunAsync();
            }
        }
    
        private static void ConfigureServices(IServiceCollection services)
        {
            // Register services with DI system
            services.AddTransient<IConfigurationService, ConfigurationService>();
            services.AddTransient<IEnvironmentService, EnvironmentService>();
    
            // DI DBContext
            services.AddDbContext<MyDBContext>(options => options.UseSqlServer(_configService.GetConfiguration().GetConnectionString("MyDBConnection")));
    
            // Other DI
            services.AddTransient<IMyService, MyService>();
        }
    
        public static string FunctionHandler(string input, ILambdaContext context)
        {
            var myService = _serviceProvider.GetService<IMyService>();
            return myService.DoSomething(input);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 2019-01-18
      • 2021-07-15
      • 1970-01-01
      • 2019-09-14
      • 2021-10-23
      相关资源
      最近更新 更多