繁体   English   中英

.Net Core - AWS Lambda 启用 DI 的项目

[英].Net Core - AWS Lambda Project enabling DI

我在 .net 核心中有一个 Lambda 项目,我想启用依赖注入。 我创建了一个 Startup class,我在其中添加了 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 核心项目有一个 Program Class ,我们会在 CreateWebHost 方法中调用启动 class ,当我们运行 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/下载要使用的模板

您可以查看 Serverless .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-3-1-lambda/

依赖注入与 Lambda 无关。 如果一切都在你的代码中,你如何处理它。

在此处查看示例实现。

https://docs.aws.amazon.com/lambda/latest/dg/dotnet-programming-model-handler-types.html

在静态方法的入口点初始化 DI 代码。

希望能帮助到你。

这是您想要的一个实施示例(对于像我这样的人不会感到迷茫)

https://github.com/Weyne/AWS-NET_CORE-NLOG/tree/main/WeyneLoggingWithNLog

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM