How Use Constractor in SignalR ChatHub ...?

Ashkan 121 Reputation points
2024-09-27T12:21:22.6233333+00:00

Hello Everyone,

I have an application, part of which I use signalr for chat and I have implemented it. Messages are sent to groups correctly and there is no problem.

At the end of the project, I decided to save each chat line in the database when sending it to the hub. Indeed, I have used Asp.net core and entity framework.

if there is No IChatService constructor, the SendMessage method will be executed correctly.

But if I add the IChatService constructor, the SendMessage method is no longer called by the JavaScript function

This Is JavaScript in Index.Cshtml:

<script>
    var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
    
    $("#sendButton").click(function () {
        var userId=$("#userId").val();
        var user = $("#username").val();
        var message = $("#message").val();
        var groupId = $("#groupid").val();
        connection.invoke("SendMessage", user, message,userId, groupId);
       });
  
</script>

and This is ChatHub Class:

public class ChatHub : Hub
{
    
    public async Task SendMessage(string user, string message, string userId, string groupId)
    {
        await Clients.Groups(groupId).SendAsync("ReceiveMessage", user, message);
              
    }
 
}


So far the program is working properly and the message is sent to the group

Now, to save the chat in the database, I add the following code to the sendmessage method:

 var chat = new ChatViewModel()
 {
     CourseId = int.Parse(groupId),
     ActDate = DateTime.Now.Date,
     ActTime = DateTime.Now.ToString("HH:mm"),
     Message = message,
     UserId = int.Parse(userId),
 };
 await _chatService.Add(chat);

And I also added the Constructor to the Class to inject IChatService:

public class ChatHub : Hub
{
    private IChatService _chatService;
    public ChatHub(IChatService chatService)
    {
        _chatService = chatService;
    }
    public async Task SendMessage(string user, string message, string userId, string groupId)
    {
        await Clients.Groups(groupId).SendAsync("ReceiveMessage", user, message);
        var chat = new ChatViewModel()
        {
            CourseId = int.Parse(groupId),
            ActDate = DateTime.Now.Date,
            ActTime = DateTime.Now.ToString("HH:mm"),
            Message = message,
            UserId = int.Parse(userId),
        };
        await _chatService.Add(chat);
    }
   
    
 }


In this case, the SendMessage method is no longer called by the JavaScript function

Please guide me where I am doing wrong

thank you

Developer technologies ASP.NET ASP.NET Core
Azure SignalR Service
Azure SignalR Service
An Azure service that is used for adding real-time communications to web applications.
161 questions
Developer technologies C#
{count} votes

Accepted answer
  1. SurferOnWww 4,631 Reputation points
    2024-09-28T01:11:34.8833333+00:00

    Did you register the ChatService to DI container? To do so code like below must be added to the Program.cs. But I can't see it in your code.

    builder.Services.AddSingleton<IChatService, ChatService>();
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-09-27T15:35:03.0533333+00:00

    signal/r does not support injection by default. you must configure support:

    https://learn.microsoft.com/en-us/aspnet/signalr/overview/advanced/dependency-injection

    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.