无法获取 Azure 函数 .Net 5.0 依赖项注入以在另一个具有依赖项的项目中注入服务



我正试图将服务注入另一个项目中的Azure函数中。

这是我的密码。

public static async Task Main()
{
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(s =>
{                    
s.AddTransient<ILocationService, LocationService>();                    
})
.Build();
Console.WriteLine("Host running!");
await host.RunAsync();            
}

LocationService依赖于DBContext。

private readonly MyAppDBContext _context;
public LocationService(MyAppDBContext context)
{
_context = context;
}

这是我的函数。

private readonly ILocationService _locationService;
private readonly TelemetryClient _telemetryClient;

public Function1(ILocationService locationService, TelemetryConfiguration telemetryConfiguration)
{
_locationService = locationService;            
_telemetryClient = new TelemetryClient(telemetryConfiguration);
}

这是错误。

结果:失败异常:System.InvalidOperationException:在尝试激活Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(type implementationType,CallSiteChain CallSiteChain,ParameterInfo[](上的"MyApp.Services.LocationService"时,无法解析类型为"MyApp.Data.MyAppDBContext"的服务parameters,Boolean throwIfCallSiteNotFound(

我已经尝试了Microsoft.Extensions.DependencyInjection.的6.0和5.0.2版本

这本指南似乎表明我做得对。

https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide#dependency-注入

非常感谢您的帮助!谢谢

原来这是Visual Studio 2019的一个问题。我无法让网络发布工作,所以我使用FTP。为此,我使用了发布到文件夹的方法。然后我压缩了文件,并使用PowerShell上传了压缩文件。结果是"发布到文件夹"方法工作不正常。它从未更新过文件。我所做的所有更改都没有进入服务器。太令人沮丧了!我在这上面浪费了好几个小时。以下是目前正在进行的工作。我还通过下载一个新的发布配置文件来修复网络发布方法。

s.AddDbContext<MyDBContext>();
s.AddLogging();
s.AddScoped<IMyService, MyService>();

最新更新