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

.NET 8独立进程Azure Functions配置SignalR时依赖注入异常

解决.NET 8独立进程Azure Functions中SignalR的ServiceManager依赖注入问题

我在采用独立进程模型的.NET 8 Azure Functions中配置SignalR时遇到错误,错误信息如下:

Exception Unable to resolve service for type 'Microsoft.Azure.SignalR.Management.ServiceManager' while attempting to activate 'PatientNavigationDBAPI.Services.SignalRService'

相关代码如下:

扩展方法代码

public static class AzureServiceExtensions
{
     public static IServiceCollection AddAzureServices(this IServiceCollection services)
     {
         //other services
         services.AddSignalR().AddAzureSignalR(Environment.GetEnvironmentVariable(EnvironmentVariable.AzureSignalRConnectionString));
         services.AddScoped<SignalRService>();
         
         return services;
     }
}

Program.cs代码

var host = new HostBuilder()
    .ConfigureFunctionsWebApplication(worker =>
    {
        worker.UseNewtonsoftJson(new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Include,
            Formatting = Formatting.Indented,
            ContractResolver = new DefaultContractResolver
            {
                NamingStrategy = new CamelCaseNamingStrategy()
            }
        });
       
    })
    .ConfigureOpenApi()
    .ConfigureServices((host, services) =>
    {
        services.AddAzureServices();
       
    })
    .Build()
    .SeedData();

host.Run();

问题原因

你当前只注册了SignalR的基础服务端集成,但ServiceManager属于Azure SignalR Management SDK的专属组件,默认不会被注入到依赖注入容器中,导致DI无法解析该类型来激活SignalRService。

解决方案

  1. 先确保项目已安装Microsoft.Azure.SignalR.Management NuGet包
  2. 修改服务注册代码,手动将ServiceManager注入到DI容器:

更新后的AddAzureServices方法:

public static class AzureServiceExtensions
{
     public static IServiceCollection AddAzureServices(this IServiceCollection services)
     {
         //other services
         services.AddSignalR().AddAzureSignalR(Environment.GetEnvironmentVariable(EnvironmentVariable.AzureSignalRConnectionString));
         
         // 注册ServiceManager到DI容器
         var signalRConnString = Environment.GetEnvironmentVariable(EnvironmentVariable.AzureSignalRConnectionString);
         services.AddSingleton<ServiceManager>(_ => 
             new ServiceManagerBuilder()
                 .WithOptions(opt => opt.ConnectionString = signalRConnString)
                 .Build());
         
         services.AddScoped<SignalRService>();
         
         return services;
     }
}

如果使用的是较新版本的Management SDK,也可以用更简洁的扩展方法:

// 替换上面的ServiceManager注册代码
services.AddAzureSignalRManagement(signalRConnString);

完成以上修改后,依赖注入容器就能正常解析ServiceManager,从而成功激活SignalRService。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 23:38:23