使用 IWebHostBuilder 在应用程序启动中执行命令时出错 "Build()"



我试图将我的API上传到AWS Lambda (Gateway),但在做我的应用程序的Build()以获得由"依赖注入"注入的服务时,我得到了一个错误,有人可以帮助我吗?

抛出初始化系统错误的代码如下:

using Amazon.Lambda.AspNetCoreServer;
using API_StoreSysBackendAdministrative.Extensions;
namespace API_StoreSysBackendAdministrative;
public class LambdaEntryPoint : APIGatewayProxyFunction
{
public static IServiceProvider ServiceProvider { get; private set; }
protected override async void Init(IWebHostBuilder builder)
{
try
{
var app =
builder
.UseContentRoot(Directory.GetCurrentDirectory())
.UseLambdaServer()
.UseStartup<Startup>()
.Build();
ServiceProvider = app.Services;
ServiceLocator.Provider = ServiceProvider;
}
catch (Exception ex)
{
throw new Exception($"{ex.Message} n Exception: {ex.ToString()}");
}
}
}

它抛出的错误如下:

Exception: System.NotSupportedException: Building this implementation of IWebHostBuilder is not supported

根据我所看到的文档,似乎Init方法应该只进行设置操作(如.UseStartup<Startup>()),实际的应用程序将由AWS框架构建:

public class LambdaEntryPoint : APIGatewayProxyFunction
{
protected override async void Init(IWebHostBuilder builder)
{
var app =
builder
.UseContentRoot(Directory.GetCurrentDirectory())
.UseLambdaServer()
.UseStartup<Startup>();
}
}

即使可以手动构建它(并且有可能构建相同的应用程序两次,在某些情况下不是),它也可能导致应用程序中的不同问题,如Singleton服务的多个实例,或缺少AWS基础设施完成的服务注册。

我强烈建议重构你的应用,这样你就不需要服务定位器了,因为它可能被认为是反模式的(我很确定有更好的方法来实现你的目标,而不是重复构建应用)。

最新更新