生产环境Azure Function间歇性抛出System.InvalidCastException问题求助
问题描述
3天前,生产环境Azure Function应用开始间歇性抛出System.InvalidCastException异常,该问题无法在预生产环境或本地复现。重启Azure Function应用后服务恢复正常。
经排查,问题疑似与NuGet包Microsoft.PowerPlatform.Dataverse.Client相关,推测和横向扩展有关,将该包从1.0.9升级至1.1.32后问题仍未解决。
异常信息
Exception while executing function: GetQueue Error constructing handler for request of type MediatR.IRequestHandler`2[Function Name space,System.Boolean]. Register your handlers with the container. See the samples in GitHub for examples. Failed to connect to Dataverse Unable to cast object of type 'generatedProxy_2' to type 'Microsoft.PowerPlatform.Dataverse.Client.IOrganizationServiceAsync'.
环境信息
- Function应用运行时版本:~4
- .NET版本:6.0
相关代码
服务注册代码
services.AddSingleton<IOrganizationServiceAsync, ServiceClient>(provider => { return GetService(d365Settings); });
public static ServiceClient GetService(D365Settings d365Settings) { var client = new ServiceClient(new Uri(d365Settings.OrganizationUri), d365Settings.ClientId, d365Settings.ClientSecret, false); if (client.IsReady) return client; throw new ArgumentException($"Unable to connect to CE, Error: {client.LastError}", client.LastException); }
项目csproj内容
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" /> <PackageReference Include="Microsoft.PowerPlatform.Dataverse.Client" Version="1.1.32" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\Core\Project1.csproj" /> <ProjectReference Include="..\..\Core\Project2.csproj" /> </ItemGroup> </Project>
解决方案建议
- 调整服务生命周期:将
ServiceClient的注册从Singleton改为Scoped或Transient。Azure Function横向扩展时,单例实例可能在不同实例间共享导致代理类型加载冲突,Scoped/Transient模式会为每个请求或作用域创建新实例,避免跨实例的类型问题。 - 禁用代理生成复用:创建
ServiceClient时,尝试通过构造重载传入自定义HttpMessageHandler,或设置ServiceClientSettings中的UseSharedHttpClient为false,禁用代理缓存。 - 增强程序集加载隔离:在Azure Function配置中启用
WEBSITE_LOAD_USER_PROFILE为true,确保所有扩展实例加载的Microsoft.PowerPlatform.Dataverse.Client程序集版本一致,避免版本差异引发的类型转换失败。 - 升级至最新稳定版:尽管已升级到1.1.32,仍建议检查该NuGet包的最新稳定版本,确认是否有针对该类型转换问题的修复。
- 添加实例初始化逻辑:使用Azure Function的
IHostedService在实例启动时单独初始化ServiceClient,确保每个实例拥有独立的客户端实例,避免跨实例资源共享。
内容的提问来源于stack exchange,提问作者Sakkie
相关产品推荐
相关产品推荐

