有一个多租户SaaS应用程序,我想在其中为SignalR Hub的OnConnectedAsync
/OnDisconnectedAsync
挂钩中的每tenantId
个创建组.
问题是ITenancyContext<ApplicationTenant>
被注册为作用域服务,这意味着它只在请求的作用域内可用.在SignalR集线器的上下文中,它与请求没有关联,因此它不可用.
那么我怎么才能让它变得可用呢?授权它并以某种方式丰富索赔吗?
public sealed class NotificationHub : Hub
{
readonly ILogger<NotificationHub> _logger;
readonly Guid _tenantId;
public NotificationHub(ILogger<NotificationHub> logger, ITenancyContext<ApplicationTenant> tenancyContext) => (_logger, _tenantId) = (logger, tenancyContext.Tenant.Id);
public override async Task OnConnectedAsync()
{
await JoinGroup(_tenantId.ToString());
_logger.LogInformation("{ConnectionId} has connected to the hub. TenantId: {TenantId}", Context.ConnectionId, _tenantId);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
await LeaveGroup(_tenantId.ToString());
_logger.LogInformation("{ConnectionId} was disconnected from the hub. TenantId: {TenantId}", Context.ConnectionId, _tenantId);
await base.OnDisconnectedAsync(exception);
}
Task JoinGroup(string groupName) => Groups.AddToGroupAsync(Context.ConnectionId, groupName);
Task LeaveGroup(string groupName) => Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
}