-
-
Notifications
You must be signed in to change notification settings - Fork 11
Services inheritance
anton-martyniuk edited this page Oct 26, 2022
·
4 revisions
Modern generic services are flexible, easily changeable and extendable. New methods can be added to service as well as each method can be overriden.
Inherit from the following interfaces:
IModernCrudService<TEntityDto, TId>
IModernQueryService<TEntityDto, TEntityDbo, TId>
Or inherit from a combined interface:
IModernService<TEntityDto, TEntityDbo, TId> : IModernCrudService<TEntityDto, TEntityDbo, TId>, IModernQueryService<TEntityDto, TEntityDbo, TId>
Lets have a look at example of inheritance from Service without caching:
public interface IAirplaneService : IModernService<AirplaneDto, AirplaneDbo, long>
{
}
public class AirplaneService : ModernService<AirplaneDto, AirplaneDbo, long, IModernRepository<AirplaneDbo, long>>, IAirplaneService
{
private readonly IMapper _mapper;
public AirplaneService(IModernRepository<AirplaneDbo, long> repository, ILogger<AirplaneService> logger, IMapper mapper)
: base(repository, logger)
{
_mapper = mapper;
}
// Override MapToDbo
protected override AirplaneDbo MapToDbo(AirplaneDto entityDto) => _mapper.Map<AirplaneDbo>(entityDto);
// Override MapToDto
protected override AirplaneDto MapToDto(AirplaneDbo entityDbo) => _mapper.Map<AirplaneDto>(entityDbo);
// Override CreateAsync
public override async Task<AirplaneDbo> CreateAsync(AirplaneDto entity, CancellationToken cancellationToken = default)
{
var entityDto = _mapper.Map<AirplaneDto>(entity);
entityDto.CreatedAt = DateTime.Now;
return await Repository.CreateAsync(entity, cancellationToken);
}
}
Lets have a look at example of inheritance from Service with caching:
public interface IAirplaneCachedService : IModernService<AirplaneDto, AirplaneDbo, long>
{
}
public class AirplaneCachedService : ModernCachedService<AirplaneDto, AirplaneDbo, long>, IAirplaneCachedService
{
private readonly IMapper _mapper;
public AirplaneCachedService(IModernService<AirplaneDto, AirplaneDbo, long> service, IModernCache<AirplaneDto, long> cache,
ILogger<AirplaneCachedService> logger, IMapper mapper)
: base(service, cache, logger)
{
_mapper = mapper;
}
// Override GetEntityId
protected override long GetEntityId(AirplaneDto entityDto) => entityDto.Id;
// Override CreateAsync
public override async Task<AirplaneDbo> CreateAsync(AirplaneDto entity, CancellationToken cancellationToken = default)
{
var entityDto = _mapper.Map<AirplaneDto>(entity);
entityDto.CreatedAt = DateTime.Now;
return await Repository.CreateAsync(entity, cancellationToken);
}
}