ASP.NET Core Web API - Error CS0103 The name 'FetchToken' does not exist in the current context

Viewed 147

I am implementing ASP.NET Core-6 Web API MediatR and Fluent Validation

I have this service:

public class MyService
{
    private readonly string baseUrl;
    private readonly ILogger<MyService> _logger;
    private readonly IMemoryCache _cache;
    public MyService(
        IConfiguration config,
        ILogger<MyService> logger,
        IMemoryCache cache
        )
    {
        _logger = logger;
        _cache = cache;
    }

    public async Task<OAuthLoginResponse> FetchToken()
    {
        string token = string.Empty;
        if (!_cache.TryGetValue("TOKEN", out token))
        {
            var tokenmodel = await this.Authenticate();
            if (tokenmodel != null)
            {
                var options = new MemoryCacheEntryOptions()
                    .SetAbsoluteExpiration(
                          TimeSpan.FromSeconds(int.Parse(tokenmodel.expires_in) - 2));

                token = JsonConvert.SerializeObject(tokenmodel);
                _cache.Set("TOKEN", token, options);
            }

        }
        return JsonConvert.DeserializeObject<OAuthLoginResponse>(token);
    }
}

Then I tried to call the FetchToken and implement it in the CommandHandler:

using Microsoft.Extensions.Logging;
using Application.Services;

public class CreateTokenInitiationCommandHandler : IRequestHandler<CreateTokenInitiationCommand, BaseResponse>
{
    private readonly IDbContext _dbContext;
    private readonly IMapper _mapper;
    private readonly ILogger<CreateTokenInitiationCommandHandler> _logger;
    //private readonly IMemoryCache _cache;
    public CreateTokenInitiationCommandHandler(IDbContext dbContext, IMapper mapper, ILogger<CreateTokenInitiationCommandHandler> logger)
    {
        _dbContext = dbContext;
        _mapper = mapper;
        _logger = logger;
    }
    public async Task<BaseResponse> Handle(CreateTokenInitiationCommand request, CancellationToken cancellationToken)
    {
        var response = new BaseResponse();
        try
        {
            var token = await FetchToken();
            var headers = new Dictionary<string, string>();
            headers.Add("Authorization", $"Bearer {token.access_token}");
        }
        catch (Exception ex)
        {
            _logger.LogError("An Error occured " + ex.ToString());
            response = new BaseResponse { response_code = "96", response_description = "Error occured, contact admin" };
        }

        return response;
    }
}

The issue is that it's not seeing FetchToken that I imported into CreateTokenInitiationCommandHandler

I got this error:

Error CS0103 The name 'FetchToken' does not exist in the current context

FetchToken is highlighted.

Even when I added using Application.Services in order to import FetchToken the error still remains

How do I resolve this?

Thanks

1 Answers

Create IMyService

public interface IMyService 
{
   Task<OAuthLoginResponse> FetchToken()
}

public class MyService : IMyService
{
    ...
    public async Task<OAuthLoginResponse> FetchToken()
    {
        ... your code
    }
}

Add It To Program.cs or Startup.cs :

builder.Services.AddScoped<IMyService, MyService>();

Then simply add it to your handler & use it :

public class CreateTokenInitiationCommandHandler : IRequestHandler<CreateTokenInitiationCommand, BaseResponse>
{
    private readonly IDbContext _dbContext;
    private readonly IMyService _service;
    private readonly IMapper _mapper;
    private readonly ILogger<CreateTokenInitiationCommandHandler> _logger;
    //private readonly IMemoryCache _cache;
    public CreateTokenInitiationCommandHandler(IDbContext dbContext, IMapper mapper, IMyService service, ILogger<CreateTokenInitiationCommandHandler> logger)
    {
        _dbContext = dbContext;
        _mapper = mapper;
        _service = service;
        _logger = logger;
    }
    public async Task<BaseResponse> Handle(CreateTokenInitiationCommand request, CancellationToken cancellationToken)
    {
        var response = new BaseResponse();
        try
        {
            var token = await _service.FetchToken();
            var headers = new Dictionary<string, string>();
            headers.Add("Authorization", $"Bearer {token.access_token}");
        }
        catch (Exception ex)
        {
            _logger.LogError("An Error occured " + ex.ToString());
            response = new BaseResponse { response_code = "96", response_description = "Error occured, contact admin" };
        }

        return response;
    }
}
Related