> 当我们使用浏览器浏览网页,是否考虑过浏览器和服务端的交互模型。

有时候,我们希望没有请求,客户端也能获取到数据,比如我们的报警版大屏、炒股的大盘。

> 长连接背后的原理是什么呢?

> SignalR就是对长连接的封装
双向的、持久的连接。
> 代码层面
如果我们封装了一个组件,该如何使用它呢?
依赖注入是后端开发中很重要的思想。
首先把需要用到的服务注入到容器中。
```
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
......
}
```
本质上是把接口和实现的关系注入到容器中。

当在接口中调用SingnalR的某些方法时,只需要从容器中取出接口即可,这样实现了接口和服务的松耦合。
```
[Route("api/broadcast")]
[ApiController]
public class BroadcastController : ControllerBase
{
private readonly IHubContext _hub;
public BroadcastController(IHubContext hub)
{
_hub = hub;
}
[HttpGet]
public async Task Get(string user, string message)
{
await _hub.Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
```
> 总结
- 本篇从客户端和服务端的交互模式开始
- 谈到了需要长连接的场景
- SingalR的封装
- 依赖注入,更到低管理接口和服务,实现低耦合