Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading