![](/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.