除了 dbContext 之外,如何向 Blazor 中的服务添加参数?
Posted
技术标签:
【中文标题】除了 dbContext 之外,如何向 Blazor 中的服务添加参数?【英文标题】:How to add a parameter to a service in Blazor in addition to the dbContext? 【发布时间】:2022-01-10 00:39:43 【问题描述】: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););
【问题讨论】:
查看这个类似问题的答案:***.com/questions/53884417/… 我做到了。我用参数创建服务没有问题。我的问题是我不知道如何将第一个作为 dbContext 传递。请查看已编辑的问题 【参考方案1】:你的注册会变得有点丑:
builder.Services.AddScoped<AccountService>(x => new AccountService(
x.GetRequiredService<MyAppDbContext>(),
newParameter));
每次您需要 AccountService 时,让 ServiceProvider 创建(作用域)DbContext 很重要。
【讨论】:
以上是关于除了 dbContext 之外,如何向 Blazor 中的服务添加参数?的主要内容,如果未能解决你的问题,请参考以下文章
除了 Unity 中的默认字符串和精灵值之外,如何向 Dropdown OptionData 添加更多 UI 元素?
DbContext.Database.SqlQuery vs ObjectContext.ExecuteFunction