asp.net – SignalR Autofac OWIN:为什么GlobalHost.ConnectionManager.GetHubContext不工作?

我正在一个项目中使用OWIN,SignalR和Autofac。

我正在设置关于signalR的内容如下:

// Create the AutoFac container builder:
        var builder = new ContainerBuilder();

        // ...[Register varIoUs other things in here]...

        // register signalR Hubs
        builder.RegisterHubs(Assembly.GetExecutingAssembly());

        // Build the container:
        var container = builder.Build();

        // Configure SignalR with the dependency resolver.
        app.MapSignalR(new HubConfiguration
        {
            Resolver =  new AutofacDependencyResolver(container)
        });

我的问题是,当我使用Autofac SignalR集成时,我无法再在服务器上获得一个signalR Hub Context(例如在webapi控制器中),因此无法从服务器端向连接的客户端发送消息。当我不使用Autofac signalR集成时,像下面这样做是这样的:

var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
hubContext.Clients.All.notification("Test Message");

但是,当我将Autofac添加到组合中时,这不起作用 – 我没有收到任何错误消息,我似乎收到了一个hubContext,但是调用它并不能真正到达客户端。

如果在对MapSignalR的调用中注释了使用依赖关系解析器对signalR的使用,则GetHubContext的调用再次工作,并且消息成功地到达了signalR客户端,但是当然我不能再在集线器上使用IoC。例如

// Configure SignalR with the dependency resolver.
        app.MapSignalR(new HubConfiguration
        {
            // Resolver =  new AutofacDependencyResolver(container)
        });

有人可以告诉我为什么使用AutofacDependencyResolver可以阻止GlobalHost.ConnectionManager.GetHubContext正常工作?

注意:我尝试过的另一件事是,而不是使用GlobalHost.ConnectionManager.GetHubContext()我尝试将IConnectionManager注入到我想要向客户端发送消息的webapi控制器中,然后调用GetHubContext,但Autofac不能解决IConnectionManager。

我确实发现了Piotr Szmyd发表的以下文章,这显然是允许的:

http://www.szmyd.com.pl/blog/wiring-signalr-with-autofac

但这似乎是基于过时的signalR构建,而在这里似乎有一个nuget包:

http://www.nuget.org/packages/SignalR.AutoFac/

它也似乎过时了。

解决方法

如果您使用SignalR的自定义依赖解析器,则除非您修改它,否则您将无法再使用GlobalHost:
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();

如果您不想修改GlobalHost,则必须手动解析您的IConnectionManager:

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

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....