我正在使用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);
}
}
IHubContext
包装中心的抽象是单例。因此,将类用作依赖项的生存期并不重要。无论您使用单例生存期,作用域生存期还是瞬态生存期,始终会获得相同的实例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句