【发布时间】:2016-05-03 18:55:04
【问题描述】:
我正在寻找一种简单的方法来通知 SignalR 集线器外部的代码关于新的客户端连接。
我该怎么做?
【问题讨论】:
标签: asp.net-mvc signalr
我正在寻找一种简单的方法来通知 SignalR 集线器外部的代码关于新的客户端连接。
我该怎么做?
【问题讨论】:
标签: asp.net-mvc signalr
您需要在您的中心类中使用Dependency Injection。
一个易于与 SignalR 集成的IoC Container 是Autofac:
public class NotifyHub : Hub
{
private readonly ILifetimeScope _hubLifetimeScope;
private readonly IHubService _hubService;
public NotifyHub(ILifetimeScope lifetimeScope)
{
// Create a lifetime scope for the hub.
_hubLifetimeScope = lifetimeScope.BeginLifetimeScope("AutofacWebRequest");
// Resolve dependencies from the hub lifetime scope.
_hubService = _hubLifetimeScope.Resolve<IHubService>();
}
public override Task OnConnected()
{
string name = Context.User.Identity.Name;
//Or whatever you want to send
_hubService.CustomNotify(name, Context.ConnectionId);
return base.OnConnected();
}
protected override void Dispose(bool disposing)
{
// Dipose the hub lifetime scope when the hub is disposed.
if (disposing && _hubLifetimeScope != null)
{
_hubLifetimeScope.Dispose();
}
base.Dispose(disposing);
}
}
另外,你需要provide dependency injection integration for SignalR hubs:
var builder = new ContainerBuilder();
//other IoC registrations
builder.RegisterType(typeof(HubService)).As(typeof(IHubService)).InstancePerRequest();
builder.RegisterType<GaugeHub>().ExternallyOwned();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);
【讨论】: