![](/img/trans.png)
[英]Net Core 2 Console App - DI 'Unable to resolve service for type…'
[英]My .NET 7 app is unable to resolve the service for a type. Already added scoped to DI
如果我已经在 DI 中注册了服务,我还缺少什么?
错误:
System.InvalidOperationException:在尝试激活“Contoso.API.Controllers.AccountsController”时无法解析“Contoso.API.Services.AccountService”类型的服务。
在 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,类型类型,类型 requiredBy,Boolean isDefaultParameterRequired)
在 lambda_method136(闭包,IServiceProvider,对象 [])
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/Accounts?email=test@example.com
[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);
}
}
我试过使用 DI 注册服务
builder.Services.AddScoped<IAccountService, AccountService>();
但我仍然收到错误提示找不到服务
我想在 program.cs 文件中注入服务的顺序可能会发生变化。
这是一个代码片段,解释了 program.cs 文件的顺序。
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
服务必须在 builder.Build() 之前注入; 之后只注入中间件。
希望这对你有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.