VS2022 NetCore 6 EF 6
builder.Services.AddDbContext<MyAppDbContext>(options removed for simplicity)
//This is my service registered on Program.cs:
builder.Services.AddScoped<AccountService>();
//This is the existing class that works as expected:
public class AccountService
{
private readonly MyAppDbContext _context;
public AccountService(MyAppDbContext context)
{
_context = context;
}
}
//So far so good...
// Now I need to add another parameter to the service:
public class AccountService
{
private readonly MyAppDbContext _context;
public AccountService(MyAppDbContext context, string newParameter)
{
_context = context;
string temp = newParameter;
}
}
// But I cannot register; I don't know what to put as first value and if I put MyAppDbContext it gives an error saying it is a type.
builder.Services.AddScoped(ServiceProvider => { return new AccountService(??, newParameter);});
// This works (no compile error) for newParameter but ignores DbContext
builder.Services.AddScoped(ServiceProvider => { return new AccountService( **null**, newParameter);});
uj5u.com熱心網友回復:
你的注冊會變得更丑一點:
builder.Services.AddScoped<AccountService>(x => new AccountService(
x.GetRequiredService<MyAppDbContext>(),
newParameter));
每次需要 AccountService 時,讓 ServiceProvider 創建(作用域)DbContext 很重要。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/378000.html
