10.1: Add Service Method and DTOs
Add IMessageService
In your .Contracts project, add a new interface called IMessageService.cs:
public interface IMessageService
{
Task<Message> GetMessage(int id);
Task<PagedList<MessageToReturn>> GetMessagesForUser();
Task<IEnumerable<MessageToReturn>> GetMessageThread(int userId, int recipientId);
Task<MessageToReturn> CreateMessage(MessageForCreation messageForCreation);
Task<bool> SaveAll();
}GetMessage() Method
In your .Services project, add a new class called MessageService.cs.
Inherit from IMessageService, ctrl + . and choose Implement interface.
For now, we'll just implement the GetMessage() and the SaveAll() methods. The CreateMessage() is much longer and we'll add that after.
public class MessageService : IMessageService
{
private readonly EFConnectContext _context;
private readonly IUserService _userService;
public MessageService(EFConnectContext context, IUserService userService)
{
_context = context;
_userService = userService;
}
public async Task<Message> GetMessage(int id)
{
return await _context.Messages
.FirstOrDefaultAsync(m => m.Id == id);
}
public Task<PagedList<MessageToReturn>> GetMessagesForUser()
{
throw new System.NotImplementedException();
}
public Task<IEnumerable<MessageToReturn>> GetMessageThread(int userId, int recipientId)
{
throw new System.NotImplementedException();
}
public Task<IEnumerable<MessageToReturn>> CreateMessage(MessageForCreation messageForCreation)
{
throw new System.NotImplementedException();
}
public async Task<bool> SaveAll()
{
return await _context.SaveChangesAsync() > 0;
}
}Register MessageService
Now, let's register our new service for dependency injection in the Startup.cs file in the .API project:
Add MessageForCreation DTO
In the .Models project, add a new folder called Message. Inside of that folder, add a new class called MessageForCreation.cs:
Add MessageToReturn DTO
Next, we'll also add a MessageToReturn DTO in the same folder:
CreateMessage() Method
Now that we have the DTOs, we can implement the CreateMessage method in our MessageService:
We're getting the recipient and sender Users based off the Id in the MessageForCreation with our UserService.
Then we're mapping the MessageForCreation to a new Message entity for us to save to the database.
Then we're returning another mapping - this time from Message to MessageToReturn.
Last updated