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>();
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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
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>();
signal/r does not support injection by default. you must configure support:
https://learn.microsoft.com/en-us/aspnet/signalr/overview/advanced/dependency-injection