我原以为只需要注册依赖项,但我发现也需要注册hubs本身才能让我的应用程序正常工作。这是预期的吗?如果是,hubs应该使用什么生命周期?
Hub methods can be called in parallel. When this happens, Hub.Context
can be overridden as part of the setup for another method call. This can lead to really subtle bugs. For example, with a singleton Hub, the following code might add a connection other than the caller to a group (which could obviously be a big security issue):
[Authorize(Roles="Admin")]
public async Task JoinAdminGroup()
{
await Groups.Add(Context.ConnectionId, "admin");
}
Hub.Dispose
will be called after each activation. If you keep returning the same Hub, it's Dispose method will be repeatedly called. This probably won't affect you unless you implement Dispose on your Hubs, since the default Dispose implementation currently no-ops.
IIS recycles AppDomains. When this happens, you will be forced to reinstantiate your Hub anyway. Remember, SignalR will automatically reestablish active connections after your app becomes unavailable for a short period of time (as is the case with an AppDomain recycle), so you can very well have a newly instantiated Hub dealing with pre-existing connections even if you register your Hub as a Singleton with the dependency resolver.
Transient
可能是更好的选择?我想我不应该感到惊讶,因为Web本质上是无状态的,所以每个方法调用都会创建/销毁中心。顺便说一下,我的服务是自托管的,而不是IIS,但我不认为这会有什么区别。 - Andrew Stephens