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);});
您的注册将变得更丑陋:
builder.Services.AddScoped<AccountService>(x => new AccountService(
x.GetRequiredService<MyAppDbContext>(),
newParameter));
每次需要AccountService时,让ServiceProvider创建(作用域(DbContext是很重要的。