Problem Injecting a interface into a interface class

I have two servives: TransactionServices and TestService, both of which implement Interfaces (ITransctionService and ITestService).
TransactionService class needs to utilize TestService. I tried the following via Dependency Injection:

Program.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();
        }
    }
}

The above produces the error below at run time:

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

So then I try consuming TestService via injection via the constructor as follows:

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();
        }
    }
}

And the above works.

Why does the first approach not work or am I missing something to make the first approach work?

>Solution :

[Inject] is not supposed to work in "normal" C# file. It is only meant to (and work in) razor components.

Use constructor injection instead! (as you do in your second sample)

Leave a Reply