.NET CORE -AWS LAMBDA项目启用DI



我在.NET核心中有一个lambda项目,并希望启用依赖注入。我创建了一个启动类,在其中添加了configureservice和configurecontainer

public class Startup
{
        public void ConfigureServices(IServiceCollection services)
        {
            void ConfigureContainer()
            {
                services.AddTransient<IProfileEventHandler, ProfileEventHandler>();
                services.AddTransient<IRepository, ESRepository>();
                services.AddTransient<IDataKeyDecryption, KmsDataKeyDecryption>();
                services.AddTransient<IDecryptionProvider, DecryptionProvider>();
            }
            ConfigureContainer();
        }
}

通常,典型的.NET核心项目具有程序类,我们将在CreateWebhost方法中调用启动类,当我们运行WebHost时,它将仅解决依赖性。但是我该如何在AWS lambda项目中做同样的事情。

您实际上可以在lambdas中使用ASP.NET Core,这当然可以更轻松地开发Web开发。如果下载Dotnet项目模板,则可以从已经具有无服务器模板和Lambda入口点的模板中创建一个项目,所有这些都配置为lambda!

使用此功能将为您提供ASP.NET Core提供的DI和IOC。

如果您正在使用VS,则可以下载Visual Studio的AWS工具包:https://aws.amazon.com/visualstudio/

另外,您可以下载通过Dotnet CLI使用的模板https://aws.amazon.com/blogs/developer/creating-net-core-aws-lambda-projects-without-visual-studio/

您可以查看无服务器.NET示例,然后从那里获取想法。它具有非常简单的实现:

  1. 创建从APIGatewayProxyFunction继承的LambdaEntryPoint类。

  2. 在此资源中添加serverless.template中的资源点。

lambdaentrypoint.cs:

public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
{
    protected override void Init(IWebHostBuilder builder)
    {
        builder.UseStartup<Startup>();
    }
}

serverless.template:

"Resources": {
    "AspNetCoreFunction": {
      "Type": "AWS::Serverless::Function",
      "Properties": {
        "Handler": "AWSServerless::AWSServerless.LambdaEntryPoint::FunctionHandlerAsync",
        "Runtime": "dotnetcore3.1",
        "Events": {
          "ProxyResource": {
            "Type": "Api",
            "Properties": {
              "Path": "/{proxy+}",
              "Method": "ANY"
            }
          },
          "RootResource": {
            "Type": "Api",
            "Properties": {
              "Path": "/",
              "Method": "ANY"
            }
          }
        }
      }
    },

关于.net lambda的好解释 - https://aws.amazon.com/blogs/developer/one-month-update-to-net-core-net-core-3-1-lambda/

最新更新