加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – SignalR Autofac OWIN:为什么GlobalHost.Connection

发布时间:2020-12-15 18:42:30 所属栏目:asp.Net 来源:网络整理
导读:我正在一个项目中使用OWIN,SignalR和Autofac。 我正在设置关于signalR的内容如下: // Create the AutoFac container builder: var builder = new ContainerBuilder(); // ...[Register various other things in here]... // register signalR Hubs builder
我正在一个项目中使用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
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读