Search code examples
asp.net-coresignalrsignalr-hubasp.net-core-signalr

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

enter image description here

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.


Solution

  • After doing some study, a solution I applied that worked for me. We Can Retrieve service object. so in startup.cs what I did given below

    Startup.cs (ConfigureServices)

      //we can retrieve service object
      public static IServiceProvider serviceProvider;
      
      services.AddSignalR()
      services.AddScoped<IUserRepository, UserRepository>();
      services.AddScoped<IMessageRepository, MessageRepository>();
    

    In my MessageHub.cs instead of using Dependency Injection I Retrieve Required Service and define it in the filed like below

    MessageHub.cs

    public class MessageHub : Hub
    {
        private readonly IMessageRepository _messageRepository;
        private readonly IUserRepository _userRepository;
    
        public MessageHub()
        {
            _messageRepository = (IMessageRepository)Startup.serviceProvider.GetRequiredService(typeof(IMessageRepository));
            _userRepository = (IUserRepository)Startup.serviceProvider.GetRequiredService(typeof(IUserRepository));
        }
    
        // other code....
    }
    

    It worked for me. Now I can implement my necessary method from IRepository and SignalR also working properly.