我正在寻找一种简单的方法来通知SignalR中心之外的关于新客户端连接的代码。
我该怎么做?
答案 0 :(得分:0)
您需要在集线器课程中使用Dependency Injection 一个IoC Container易于与SignalR集成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);