asp.Net   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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
});

大佬总结

以上是大佬教程为你收集整理的asp.net – SignalR Autofac OWIN:为什么GlobalHost.ConnectionManager.GetHubContext不工作?全部内容,希望文章能够帮你解决asp.net – SignalR Autofac OWIN:为什么GlobalHost.ConnectionManager.GetHubContext不工作?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。