My .NET 7 app is unable to resolve the service for a type. Already added scoped to DI

826 Views Asked by At

If I already registered the service in DI what am I missing?

Error:

System.InvalidOperationException: Unable to resolve service for type 'Contoso.API.Services.AccountService' while attempting to activate 'Contoso.API.Controllers.AccountsController'.

at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method136(Closure, IServiceProvider, Object[])

Program.cs:

builder.Services.AddDbContext<FinanceDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("FinanceDb")));

builder.Services.AddScoped<IAccountService, AccountService>();

IAccountService.cs:

public interface IAccountService
{
    Task<IList<Account>> GetAccountsAsync(string email);
}

AccountService.cs:

public class AccountService : IAccountService
{
    private readonly FinanceDbContext _dbContext;

    public AccountService(FinanceDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<IList<Account>> GetAccountsAsync(string email)
    {
        // Retrieve the user with the provided email address
        var user = await _dbContext.Users.Include(x => x.Accounts).FirstOrDefaultAsync(u => u.Email == email);

        // Return the user's accounts
        return user.Accounts;
    }
}

AccountsController.cs:

public class AccountsController : ControllerBase
{
    private readonly IAccountService _accountService;

    public AccountsController(IAccountService accountService)
    {
        _accountService = accountService;
    }

    // GET: api/[email protected]
    [HttpGet]
    public async Task<ActionResult<IList<Account>>> GetAccounts([FromQuery] string email)
    {
        // Retrieve the user's accounts based on the provided email address
        var accounts = await _accountService.GetAccountsAsync(email);

        // Return the list of accounts
        return Ok(accounts);
    }
}

I've tried registering the service with DI using

builder.Services.AddScoped<IAccountService, AccountService>(); 

but I still get the error saying it can't find the service

1

There are 1 best solutions below

0
Srinivethaa Pongiannan On

I guess there might be a change in order of injecting the services in program.cs file.

Here is an code snippets explains the order of the program.cs file.

var builder = WebApplication.CreateBuilder(args);

 
builder.Services.AddControllers();
// Add services 
builder.Services.AddDbContext<FinanceDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("FinanceDb")));


builder.Services.AddScoped<IAccountService, AccountService>();


var app = builder.Build();

 
// add middlewares here

The Services must be injected before the builder.Build(); after that only the middlewares are be injected.

Hope this might help you.