SignalR + Autofac + OWIN: Why doesn't GlobalHost.ConnectionManager.GetHubContext work?

痞子三分冷 提交于 2019-11-28 19:12:05

If you use a custom dependency resolver with SignalR, you can no longer use GlobalHost unless you modify it:

GlobalHost.DependencyResolver = new AutofacDependencyResolver(container);
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();

// A custom HubConfiguration is now unnecessary, since MapSignalR will
// use the resolver from GlobalHost by default.
app.MapSignalR();

If you don't want to modify GlobalHost, you will have to manually resolve your IConnectionManager:

IDependencyResolver resolver = new AutofacDependencyResolver(container);
IHubContext hubContext = resolver.Resolve<IConnectionManager>().GetHubContext<MyHub>();

app.MapSignalR(new HubConfiguration
{
    Resolver = resolver
});

For a complete answer, with SignalR, Autofac, and OWIN, I did the following:

// register IPersistantConnectionContext for access to SignalR connection
// and IDependencyResolver to enable inection of the container into its
// construction for the config object.
var builder = new ContainerBuilder();
builder.RegisterType<Autofac.Integration.SignalR.AutofacDependencyResolver>()
    .As<IDependencyResolver>()
    .SingleInstance();
builder.Register((context, p) =>
        context.Resolve<IDependencyResolver>()
            .Resolve<Microsoft.AspNet.SignalR.Infrastructure.IConnectionManager>()
            .GetConnectionContext<SignalRConnection>());

// ... other registrations

var container = builder.Build();

var signalrConfiguration = new ConnectionConfiguration
{
    Resolver = container.Resolve<IDependencyResolver>(),
};

app.UseAutofacMiddleware(container);

app.MapSignalR<SignalRConnection>("/signalr", signalrConfiguration);

// ... other middleware

In my controllers, I included a parameter of the type IPersistentConnectionContext and the correct instance is injected.

I was using a PersistentConnection, but it should be similar for Hubs.

To expand on Nathan's answer, I am using something similar with the key line being

builder.RegisterHubs(Assembly.GetExecutingAssembly()).SingleInstance();

in Startup.cs.

The line "SingleInstance()" ensures that only a single "instance" of the hub is used throughout the application.

Then I just use straightforward dependency injection into the constructor of the controller to get a pointer to the hub.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!