【问题标题】:Problem Injecting a interface into a interface class [duplicate]将接口注入接口类的问题[重复]
【发布时间】: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


    【解决方案1】:

    [Inject] 不应该在“普通”C# 文件中工作。它仅用于(并用于)剃须刀组件。

    改用构造函数注入! (就像你在第二个样本中所做的那样)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 2015-04-06
      • 2011-09-08
      • 1970-01-01
      • 2020-09-07
      相关资源
      最近更新 更多