SignalR getting disconnected while applying Dependency Injection

MH DIP 1 Reputation point
2022-05-19T10:48:24.593+00:00

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
Azure SignalR Service
An Azure service that is used for adding real-time communications to web applications.
147 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,706 Reputation points
    2022-05-19T20:13:26.377+00:00

    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.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.