我有 DI 问题。我有自定义类,应该通过服务将一些数据导入数据库。如果我在 Blazor 组件中使用此服务,则它与 @injection 配合良好。
但是我无法在我的自定义类中使用它。我这样试过
public class ImportXml
{
private readonly AccountService _accountService;
public ImportXml(AccountService accountService)
{
_accountService = accountService;
}
public ImportXml(List<Transaction> transactions, Account account)
{
if(account.Transactions==null)
{
account.Transactions = new List<Transaction>();
}
account.Transactions.AddRange(transactions);
_accountService.UpdateAccountsAsync(account);
}
}
在startup.cs中是这样注册的服务。
services.AddScoped<AccountService>();
如果我调用 ImportXml _accountService 为空。
我目前的解决方法是将服务作为参数的一部分发送。但我希望有 DI 的可行解决方案。
public class ImportXml
{
public ImportXml(List<Transaction> transactions, Account account, AccountService accountService)
{
if(account.Transactions==null)
{
account.Transactions = new List<Transaction>();
}
account.Transactions.AddRange(transactions);
accountService.UpdateAccountsAsync(account);
}
}
非常感谢
答案 0 :(得分:1)
这里有几个问题。
更改您的 ImportXml 类
public class ImportXml
{
private readonly AccountService _accountService;
// This it the constructor, so just set the object up
public ImportXml(AccountService accountService)
{
_accountService = accountService;
}
// This is the method to perform the update
public async Task DoAccountUpdateAsync(
List<Transaction> transactions,
Account account)
{
if(account.Transactions==null)
{
account.Transactions = new List<Transaction>();
}
account.Transactions.AddRange(transactions);
await _accountService.UpdateAccountsAsync(account);
}
}
同时注册 AccountService 和 ImportXml
services.AddScoped<AccountService>();
services.AddScoped<ImportXml>();
从客户端,注入 ImportXml,然后使用该服务。 当ImportXml被注入时,它的构造函数参数(AccountService)会由DI自动提供并注入到ImportXml中。
@inject ImportXML ImportXML
<button @onclick=@HandleClick>Perform Account Update</button>
@code {
List<Transactions> _transactionsForMethod;
Account _accountForMethod;
async Task HandleClick()
{
await ImportXML.DoAccountUpdateAsync(
_transactionsForMethod,
_accoountForMethod);
}
}