使用SignalR集线器的服务的推荐生命周期

问题描述 投票:0回答:1

我正在使用SignalR ContentHub在ASP.NET Core Web应用程序(在.NET Core 2.2中运行)的各种控制器中注入以下服务。当前,该服务注入了短暂的生命周期。使用单例生命周期会更好吗?在这种情况下,过渡生命周期是否可能导致性能问题?

public class PushMessageService : IPushMessageService
{
    private readonly ILogger<PushMessageService> _logger;
    private readonly IHubContext<ContentHub> _context;

    public PushMessageService(
        ILogger<PushMessageService> logger,
        IHubContext<ContentHub> context
    )
    {
        _logger = logger;
        _context = context;
    }    

    public async Task Push(int productId)
    {
        var msg = new Message
        {
            ProductId = productId
        };

        await SendAsync("PushMsg", productId, msg);
    }

    private async Task SendAsync<TPayload>(string methodName, int productId, TPayload payload)
    {
        await _context.Clients.Group("prod" + productId).SendAsync(methodName, payload);
    }
}
asp.net-core signalr asp.net-core-signalr
1个回答
0
投票

SignalR希望分别为每个消息创建集线器。如果希望集线器位于DI中,则需要将其添加为Transient服务。通常,您不应该用DI解决集线器。如果需要在集线器和其他组件之间共享代码,建议您使用IHubContext或将共享代码放在单独的DI服务中,如此处所示。因此,我认为这应该是暂时的。

© www.soinside.com 2019 - 2024. All rights reserved.