除了 dbContext 之外,如何向 Blazor 中的服务添加参数?
How to add a parameter to a service in Blazor in addition to the dbContext?
VS2022 网核 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 很重要。
VS2022 网核 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 很重要。