【问题标题】:Signalr not working with Autofac and WebAPI + MVC + OWINSignalr 不适用于 Autofac 和 WebAPI + MVC + OWIN
【发布时间】:2020-04-18 06:07:11
【问题描述】:

我们正在尝试使用 Autofac 启动具有依赖注入的 Signalr Hub,但还没有结果。 MVC 和 Web API 与 DI 配合得很好。

这里是配置文件。

Startup.cs

[assembly: OwinStartupAttribute(typeof(PNAME.WebUI.Startup))]
namespace PNAME.WebUI
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            // Register Routes
            WebApiConfig.Register(config);

            // Register dependencies
            //ConfigureDependencies(app, config);
            var container = DependencyConfiguration.Configure(app);
            SignalRConfiguration.Configure(app, container);
            MvcConfiguration.Configure(app, container);
            WebApiConfiguration.Configure(app, container, config);
            // Configure Authentication middleware
            ConfigureAuth(app, config);

            // configure Web API 
            app.UseWebApi(config);
        }
    }
}

DependencyConfiguration.cs

  public static class DependencyConfiguration
    {
        public static IContainer Configure(IAppBuilder app)
        {
            var builder = new ContainerBuilder();


            //Register any other components required by your code....
            builder.RegisterType<MainContext>().As<IApplicationDbContext>();

            builder.RegisterType<OneSignalNotificationService>().As<IPushNotificationService>();

            builder.RegisterType<LogService>().As<ILogger>();

            //Register SignalR Hub
            builder.RegisterHubs(Assembly.GetExecutingAssembly());
            //builder.RegisterType<ChatHub>().ExternallyOwned();

            //Register MVC Controllers
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            //Register WebApi Controllers
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());

            var container = builder.Build();
            app.UseAutofacMiddleware(container);
            return container;
        }
    }

WebApiConfiguration.cs

public class WebApiConfiguration
    {
        public static void Configure(IAppBuilder app, IContainer container, HttpConfiguration config)
        {
            // Set the dependency resolver for Web API.
            var webApiResolver = new AutofacWebApiDependencyResolver(container);
            config.DependencyResolver = webApiResolver;

            //Configure Action Injection
            //config.InjectInterfacesIntoActions();

            app.UseAutofacWebApi(config);
        }
    }

SignalRConfiguration.cs

  public static class SignalRConfiguration
    {
        public static void Configure(IAppBuilder app, IContainer container)
        {
            //var config = new HubConfiguration();
            //config.Resolver = new AutofacDependencyResolver(container);
            //config.EnableDetailedErrors = true;

            //app.MapSignalR("/signalr", config);

            app.Map("/signalr", map =>
            {
                map.UseAutofacMiddleware(container);

                var hubConfiguration = new HubConfiguration
                {
                    Resolver = new AutofacDependencyResolver(container),
                    EnableDetailedErrors = true
                };

                map.RunSignalR(hubConfiguration);
            });
        }
    }

MvcConfiguration.cs

public class MvcConfiguration
    {
        public static void Configure(IAppBuilder app, IContainer container)
        {
            var mvcResolver = new Autofac.Integration.Mvc.AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(mvcResolver);

            app.UseAutofacMvc();
        }
    }

至于ChatHub,其作为类库位于另一个项目中,不同的namespace如下

ChatHub.cs

namespace PNAME.BotServices.NotificationCenter.SignalR
{
    [HubName("ChatHub")]
    public class ChatHub : Hub
    {
        private ILogger _logger;
        //private IChatMessageServices _chatMessageServices;
        private readonly ILifetimeScope _hubLifetimeScope;

        public ChatHub(ILifetimeScope lifetimeScope)
        {
            // Create a lifetime scope for the hub.
            _hubLifetimeScope = lifetimeScope.BeginLifetimeScope("AutofacWebRequest");

            // Resolve dependencies from the hub lifetime scope.
            _logger = _hubLifetimeScope.Resolve<ILogger>();
           // _chatMessageServices = _hubLifetimeScope.Resolve<IChatMessageServices>();

        }

        public bool SendMessage(INotificationMessage notificationMessage)
        {
           //Some code here
        }
        public override Task OnConnected()
        {
            //Some code here
        }
        public override Task OnReconnected()
        {
             //Some code here
        }
        public async Task UpdateStatus(int messageId, int ServerId, StatusType status)
        {
             //Some code here
        }

        protected override void Dispose(bool disposing)
        {
            // Dispose the hub lifetime scope when the hub is disposed.
            if (disposing && _hubLifetimeScope != null)
            {
                _hubLifetimeScope.Dispose();
            }

            base.Dispose(disposing);
        }

    }
}

这就是所有的配置。

正如我在 MVC 和 API 控制器中所说,仅 DI 信号器与未从客户端连接并失败并出现以下错误的情况下运行良好。

Microsoft.AspNet.SignalR.Client.HttpClientException: StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Transfer-Encoding: chunked
  X-SourceFiles: =?UTF-8?B?RDpcUHJvamVjdHNcQk9UUmVwb1xCT1Rcc2lnbmFsclxuZWdvdGlhdGU=?=
  Cache-Control: private
  Date: Sat, 28 Dec 2019 20:43:45 GMT
  Server: Microsoft-IIS/10.0
  X-AspNet-Version: 4.0.30319
  X-Powered-By: ASP.NET
  Content-Type: text/html; charset=utf-8
}
   at Microsoft.AspNet.SignalR.Client.Http.DefaultHttpClient.<>c__DisplayClass5_0.<Get>b__1(HttpResponseMessage responseMessage)
   at Microsoft.AspNet.SignalR.TaskAsyncHelper.<>c__DisplayClass31_0`2.<Then>b__0(Task`1 t)
   at Microsoft.AspNet.SignalR.TaskAsyncHelper.TaskRunners`2.<>c__DisplayClass3_0.<RunTask>b__0(Task`1 t)

不知道我在这个配置中错过了什么。

【问题讨论】:

  • 您只显示异常的堆栈跟踪。所以你有错误信息?您能否附加一个调试器来捕获异常并获取完整消息?
  • 调试器中未显示错误。尝试从 javascript 应用程序连接到集线器后,控制台中显示错误,这是由于 Chathub 名称中的重复。所以更改集线器名称解决了这个问题。谢谢。

标签: asp.net-web-api model-view-controller signalr owin autofac


【解决方案1】:

问题在于将 Hub 名称更改为“MyChatHub”后的 Hub 名称,依赖注入一切正常

【讨论】:

    猜你喜欢
    • 2019-02-09
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多