我已经使用.net核心版本1.0 AWS.Net SDK创建了Lambda函数。我想实现依赖注入(inject)。由于lambda函数在AWS环境中独立触发和运行,因此不存在类似Startup的类。如何以及在何处配置容器以实现此实现?

最佳答案

你可以这样做。您的FunctionHandler是您应用程序的入口点。因此,您必须从那里连接服务集合。

public class Function
{
    public string FunctionHandler(string input, ILambdaContext context)
    {
        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);

        // create service provider
        var serviceProvider = serviceCollection.BuildServiceProvider();

        // entry to run app.
        return serviceProvider.GetService<App>().Run(input);
    }

    private static void ConfigureServices(IServiceCollection serviceCollection)
    {
        // add dependencies here

        // here is where you're adding the actual application logic to the collection
        serviceCollection.AddTransient<App>();
    }
}

public class App
{
    // if you put a constructor here with arguments that are wired up in your services collection, they will be injected.

    public string Run(string input)
    {
        return "This is a test";
    }
}

如果要连接日志记录,请在此处查看:https://github.com/aws/aws-lambda-dotnet/tree/master/Libraries/src/Amazon.Lambda.Logging.AspNetCore

10-05 18:40