DB服务的依赖注入

时间:2021-06-17 22:47:19

标签: class dependency-injection entity-framework-core blazor-server-side

我有 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);
           
    }
    }

非常感谢

1 个答案:

答案 0 :(得分:1)

这里有几个问题。

  1. 为了让ImportXml通过DI接收AccountService,DI容器也需要提供ImportXml。
  2. 您正在使用第二个构造函数来尝试执行操作,而不是使用方法。构造函数应该只用于设置类,而不是执行任何操作,尤其是长时间运行的操作,例如更新数据库。另请注意,构造函数不是异步的。

更改您的 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);
    }
}
相关问题