NET 6 - Service/Business Layer

Last modified: March 26, 2022

This is business layer, where user requirments happen.

In this tutorial, it might look Business is not needed but in complex it is. This is becuase we have any Data Access layer (e.g. EF Core or Dapper). In additional to this, it is easily to put all business logic in a same project.

1. Install AutoMapper

automapper

Install AutoMapper NuGet package, then create a folder named AutoMapper in your root of the TicketingSystem.Service project. Inside that folder, we are going to create AutoMapperProfile.cs class where we configure the automapper as shown below. We map both side for example CreateMap<Event, EventViewModel>().ReverseMap();, Event Model map to EventViewModel and EventViewModel map to Event (with the help of ReverseMap() method)

2. ViewModels

  • Select TicketingSystem.Service project

  • Create a folder name Services

  • Create a class named EventService

    public class EventService { private readonly EventRepository _repository; private readonly IMapper _mapper; public EventService(EventRepository repository, IMapper mapper) { _repository = repository; _mapper = mapper; } public async Task<IEnumerable<Event>> GetAllAsync() { return await _repository.GetAll(); } public async Task<Event> GetById(int id) { return await _repository.GetById(id); } public async Task<bool> Delete(int id) { return await _repository.Remove(id); } public async Task<bool> Update(Event entity) { return await _repository.Update(entity); } }
    • Create EventBookingService and save to Services

EventBookingService

public class EventBookingService { private readonly IEventRepository _eventRepository; private readonly IEventBookingRepository _bookingRepository; private readonly IMapper _mapper; public EventBookingService(IEventRepository eventRepository, IEventBookingRepository bookingRepository, IMapper mapper) { _eventRepository = eventRepository; _bookingRepository = bookingRepository; _mapper = mapper; } public async Task<List<EventBookingViewModel>> GetAllAsync() { var booking = await _bookingRepository.GetAll(); return _mapper.Map<List<EventBookingViewModel>>(booking); } public async Task<bool> AddEventBooking(EventBooking eventBooking) { return await _bookingRepository.Add(eventBooking); } }

`