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.
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
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.