【发布时间】:2022-12-20 04:40:47
【问题描述】:
我有两个服务:TransactionServices 和 TestService,它们都实现了接口(ITransctionService 和 ITestService)。 TransactionService 类需要利用 TestService。我通过依赖注入尝试了以下操作:
程序.cs:
builder.Services.AddScoped<ITestService, TestService>();
services/TransactionService.cs:
namespace Accounting.Web.Services
{
public class TransactionService : ITransactionService
{
[Inject]
private ITestService TestService { get; set; }
public async void LoadTransactions(int Year, int Month)
{
_testService.Test();
}
}
}
以上在运行时产生以下错误:
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at Accounting.Web.Services.TransactionService.LoadTransactions(Int32 Year, Int32 Month) in E:\aspnet\Accounting.Web\Services\TransactionService.cs:line 24
at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__128_1(Object state)
at System.Threading.QueueUserWorkItemCallbackDefaultContext.Execute()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading.ThreadPool.Callback()
ThreadPool Callback threw an unhandled exception of type System.NullReferenceException
因此,我尝试通过构造函数通过注入来使用 TestService,如下所示:
namespace Accounting.Web.Services
{
public class TransactionService : ITransactionService
{
private ITestService _testService;
public TransactionService(ITestService testService)
{
_testService = testService;
}
public async void LoadTransactions(int Year, int Month)
{
_testService.Test();
}
}
}
以上作品。
为什么第一种方法不起作用,或者我错过了使第一种方法起作用的东西?
【问题讨论】:
标签: c# asp.net-core blazor blazor-server-side blazor-webassembly