123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- using Microsoft.Extensions.Caching.Memory;
- using System;
- using System.Threading.Tasks;
- using Znaf.Application.Communication;
- using Znaf.Application.Interfaces;
- using Znaf.Domain.Interfaces;
- using Znaf.Domain.Models;
- using Znaf.Domain.Models.Queries;
- using Znaf.Infra.CrossCutting.Bus;
- namespace Znaf.Application.Services
- {
- /// <summary>
- /// 车辆服务
- /// </summary>
- public class VehicleAppService : IVehicleAppService
- {
- private readonly IUnitOfWork _unitOfWork;
- private readonly IMemoryCache _cache;
- private readonly IVehicleRepository _vehicleRepository;
- public VehicleAppService(IUnitOfWork unitOfWork, IMemoryCache cache, IVehicleRepository vehicleRepository)
- {
- _unitOfWork = unitOfWork;
- _cache = cache;
- _vehicleRepository = vehicleRepository;
- }
- public async Task<QueryResult<Vehicle>> ListVehicles(VehicleQuery query)
- {
- var cacheKey = GetCacheKeyForVehicleQuery(query);
- var vehicles = await _cache.GetOrCreateAsync(cacheKey, entry =>
- {
- entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1);
- return _vehicleRepository.GetByPagination(query);
- });
- return vehicles;
- }
- public async Task<VehicleResponse> AddAsync(Vehicle vehicle)
- {
- try
- {
- var existVehicle = await _vehicleRepository.FindByGuidAsync(vehicle.Guid);
- if (existVehicle != null)
- {
- return new VehicleResponse("已存在");
- }
- await _vehicleRepository.AddAsync(vehicle);
- await _unitOfWork.CompleteAsync();
- return new VehicleResponse(vehicle);
- }
- catch (Exception e)
- {
- return new VehicleResponse($"新增时出现错误:{e.Message}");
- }
- }
- public async Task<VehicleResponse> UpdateAsync(string guid, Vehicle vehicle)
- {
- var existVehicle = await _vehicleRepository.FindByGuidAsync(guid);
- if (existVehicle == null)
- {
- return new VehicleResponse("未找到车辆信息");
- }
- //todo 更新数据
- try
- {
- _vehicleRepository.Update(existVehicle);
- await _unitOfWork.CompleteAsync();
- return new VehicleResponse(existVehicle);
- }
- catch (Exception e)
- {
- return new VehicleResponse($"更新出现问题:{e.Message}");
- }
- }
- public async Task<VehicleResponse> DeleteAsync(string guid)
- {
- var existVehicle = await _vehicleRepository.FindByGuidAsync(guid);
- if (existVehicle == null)
- {
- return new VehicleResponse("未找到车辆信息");
- }
- try
- {
- _vehicleRepository.Remove(existVehicle);
- await _unitOfWork.CompleteAsync();
- return new VehicleResponse(existVehicle);
- }
- catch (Exception e)
- {
- return new VehicleResponse($"删除出现问题:{e.Message}");
- }
- }
- private static string GetCacheKeyForVehicleQuery(VehicleQuery query)
- {
- var key = CacheKeys.VehiclesList.ToString();
- key = string.Concat(key, "_", query.Page, "_", query.ItemsPerPage);
- return key;
- }
- }
- }
|