question

MHDIP-9523 avatar image
0 Votes"
MHDIP-9523 asked YijingSun-MSFT edited

SignalR getting disconnected while applying Dependency Injection

I am new to SignalR and building a live chat by using .NET 5 and angular 13. While establishing the connection it is giving this error-- Connection closed with an error. NullReferenceException

203676-q1.png




After multiple debagging I found out what is the root cause of the problem. When I inject any dependency to my message hub. NullReferenceException error is happened. without dependency the connection is established properly.

here is my MessageHub.cs code (with dependency)

 public class MessageHub : Hub
 {
     private readonly IMessageRepository _messageRepository;
     private readonly IUserRepository _userRepository;
    
     public MessageHub(IMessageRepository messageRepository, IUserRepository userRepository)
     {
         _messageRepository = messageRepository;
         _userRepository = userRepository;
     }
    
    
     public override async Task OnConnectedAsync()
     {
         var httpContext = Context.GetHttpContext();
    
         var otherUser = httpContext.Request.Query["user"].ToString();
    
         var groupName = GetGroupName(Context.User.GetUsername(), otherUser);
    
         await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
     }
    
     public override async Task OnDisconnectedAsync(Exception exception)
     {
         await base.OnDisconnectedAsync(exception);
     }
    
 }

Startup.cs (ConfigureServices)

  services.AddSignalR(e=>
         {
             e.EnableDetailedErrors = true;               
         });

Startup.cs (Configure)

  app.UseEndpoints(endpoints =>
         {
             endpoints.MapControllers();
             endpoints.MapHub<MessageHub>("hubs/message");
         });

I extremely need this dependency to complete my functionality. I got stack with this. If I remove the Dependency it works fine. I tried to find some solution from various sources but didn't work for me. if anyone help me. I will be really appreciate for this.

azure-signalr-service
q1.png (24.8 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered

your dependency objects are probably throwing the exception. as your hub is not using calling any of their methods, its probably one of their constructors.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.