admin管理员组

文章数量:1410689

For context: I use Mapster and Serilog.

public class UserService(IUserRepository repository, ILogger logger)
{
    public async Task<TDto?> GetByIdAsync<TDto>(int userId, Func<IQueryable<User>, IQueryable<User>>? include = null,
        CancellationToken cancellationToken = default)
    {
        try
        {
            var entity = await repository.GetByIdAsync(userId, include, cancellationToken);
 
            return entity is null ? default : entity.Adapt<TDto?>();
        }
        catch (OracleException ex) when (ex.Number == 1013)
        {
            logger.Information("The request was cancelled.");
            return default;
        }
    }
 
    public async Task<IEnumerable<TDto>> GetByNameAsync<TDto>(string name,
        CancellationToken cancellationToken = default)
    {
        try
        {
            var entities = await repository.GetByNameAlnumAsync(name, cancellationToken);
 
            return entities.Adapt<IEnumerable<TDto>>();
        }
        catch (OracleException ex) when (ex.Number == 1013)
        {
            logger.Information("The request was cancelled.");
            return [];
        }
    }
 
    public async Task<IEnumerable<TDto>> GetByFilterAsync<TDto>(Filter filter,
        CancellationToken cancellationToken = default)
    {
        try
        {
            var entities = await repository.GetByFilterAsync(filter, cancellationToken);
 
            return entities.Adapt<IEnumerable<TDto>>();
 
        }
        catch (OracleException ex) when (ex.Number == 1013)
        {
            logger.Information("The request was cancelled.");
            return [];
        }
    }
}

Questions:

  1. Am I using TDto correctly?
  2. The include argument in the GetByIdAsync method violates SRP. Let's say User has many external dependencies, and they are used in different ways everywhere. For each use, make a method that differs from many similar ones by another set of .Include()?
  3. What is the best way to anize try catch blocks? Result object? What about repeatability? I shouldn't make a method in this service that will handle Exception, right? Handler service? What information should be passed on?

本文标签: cHow to properly organize (User)Service DTOInclude and exception handlingStack Overflow