You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Lambda(.NET 6)依赖注入报错:无参构造函数未定义

在AWS Lambda的C# .NET 6代码中使用依赖注入遇到无参构造函数错误

无法动态创建'TestDep.Function'类型的实例,原因是未定义无参构造函数。

已安装以下NuGet包:

Amazon.Lambda.Annotations;
Microsoft.Extensions.DependencyInjection;

Startup.cs

using System;
using Amazon.Lambda.Annotations;
using Microsoft.Extensions.DependencyInjection;

namespace TestDep
{
    [LambdaStartup]
    public class Startup
    {
        public void ConfigureServices(IServiceCollection serviceCollection)
        {
            serviceCollection.AddTransient<IMyDependency, MyDependency>();

        }
    }
}

接口定义

namespace TestDep
{
    public interface IMyDependency
    {
        string GetValue(string key);
    }
}

实现类 MyDependency.cs

using System;
namespace TestDep
{
    public class MyDependency : IMyDependency
    {
        public MyDependency()
        {
            Value = Guid.NewGuid();
        }

        public Guid Value { get; private set; }

        public string GetValue(string key)
        {
            return $"MyDependency {key} {Value}";

        }
    }
}

Function类

using Amazon.Lambda.Annotations;
using Amazon.Lambda.Core;

// 程序集特性:允许将Lambda函数的JSON输入转换为.NET类
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace TestDep;

public class Function
{
    private readonly IMyDependency _myDependencyCtor;
    public Function(IMyDependency myDependency)
    {
        _myDependencyCtor = myDependency;

    }

    /// <summary>
    /// 接收字符串并返回处理结果的简单函数
    /// </summary>
    /// <param name="input"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    [LambdaFunction]
    public List<string> FunctionHandler(string a, ILambdaContext context)
    {
        return new List<string>()
        {
            _myDependencyCtor.GetValue("Constructor"),
            a
        };
    }
}

aws-lambda-tools-defaults.json

{
  "Information": [
    "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
    "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
    "dotnet lambda help",
    "All the command line options for the Lambda command can be specified in this file."
  ],
  "profile": "",
  "region": "",
  "configuration": "Release",
  "function-architecture": "x86_64",
  "function-runtime": "dotnet6",
  "function-memory-size": 256,
  "function-timeout": 30,
  "function-handler": "TestDep::TestDep.Function::FunctionHandler"
}

serverless.template

{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Transform": "AWS::Serverless-2016-10-31",
  "Description": "This template is partially managed by Amazon.Lambda.Annotations (v1.0.0.0).",
  "Resources": {
    "TestDepFunctionFunctionHandlerGenerated": {
      "Type": "AWS::Serverless::Function",
      "Metadata": {
        "Tool": "Amazon.Lambda.Annotations"
      },
      "Properties": {
        "Runtime": "dotnet6",
        "CodeUri": ".",
        "MemorySize": 256,
        "Timeout": 30,
        "Policies": [
          "AWSLambdaBasicExecutionRole"
        ],
        "PackageType": "Zip",
        "Handler": "TestDep::TestDep.Function_FunctionHandler_Generated::FunctionHandler"
      }
    }
  }
}

变通方案(可实现依赖注入并支持单元测试)

原方案未解决问题,以下是替代实现:

public class Function
{
    private readonly IMyDependency _myDependencyCtor;
    public Function()
    {
        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);
        var serviceProvider = serviceCollection.BuildServiceProvider();

        // 从DI容器获取服务
        _myDependencyCtor = serviceProvider.GetService<IMyDependency>();

    }
    public Function(IMyDependency myDependency)
    {
        _myDependencyCtor = myDependency;

    }
    private void ConfigureServices(IServiceCollection serviceCollection)
    {
        // 向DI容器注册服务
        serviceCollection.AddTransient<IMyDependency, MyDependency>();
    }

    /// <summary>
    /// 接收字符串并返回处理结果的简单函数
    /// </summary>
    /// <param name="input"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    [LambdaFunction]
    public List<string> FunctionHandler(string a, ILambdaContext context)
    {
        return new List<string>()
        {
            _myDependencyCtor.GetValue("Constructor"),
            a
        };
    }
}

内容的提问来源于stack exchange,提问作者Adilp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 04:43:24