在Azure Functions应用中使用Semantic Kernel时遇方法未找到异常求助
问题背景
我创建了一个基础的Azure Functions示例应用,尝试在其中使用Semantic Kernel,执行以下代码时出现错误:
var builder = Kernel.CreateBuilder(); builder.Services.AddAzureOpenAIChatCompletion(azureOpenAIDeploymentName, azureOpenAIEndpoint, azureOpenAIAPIKey);
错误信息:
System.MissingMethodException: 'Method not found: 'Microsoft.Extensions.DependencyInjection.IServiceCollection Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddKeyedSingleton(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Object, System.Func`3<System.IServiceProvider,System.Object,!!0>)'.'
原因分析
这个异常的核心原因是依赖版本不兼容:
- 新版Semantic Kernel依赖
Microsoft.Extensions.DependencyInjection包中的AddKeyedSingleton方法,该方法是在.NET 7及对应的Extensions包(版本≥7.0.0)中新增的。 - Azure Functions默认环境(比如.NET 6 runtime)所依赖的
Microsoft.Extensions.DependencyInjection版本较低,不包含该方法,导致调用时找不到对应方法。
解决办法
方法1:升级Azure Functions的.NET版本到.NET 7+
这是最稳妥的解决方案:
- 打开项目的
.csproj文件,将TargetFramework修改为net7.0或更高,同时确保Azure Functions SDK版本为v4:<PropertyGroup> <TargetFramework>net7.0</TargetFramework> <AzureFunctionsVersion>v4</AzureFunctionsVersion> </PropertyGroup> - 重新还原依赖并构建项目:
dotnet restore dotnet build
方法2:显式升级依赖包版本
如果暂时无法升级.NET版本,可尝试显式安装满足要求的Microsoft.Extensions.DependencyInjection包:
dotnet add package Microsoft.Extensions.DependencyInjection --version 7.0.0
注意:此方法可能引发Azure Functions其他依赖的兼容性问题,需谨慎测试。
方法3:降级Semantic Kernel到兼容版本
若必须保留当前Azure Functions的.NET版本,可降级Semantic Kernel到不依赖AddKeyedSingleton的旧版本,例如:
dotnet add package Microsoft.SemanticKernel --version 0.21.230828.2-preview
内容的提问来源于stack exchange,提问作者Supreet
相关产品推荐
相关产品推荐

