.NET register services for interface, base class and sub class dependency injection

545 Views Asked by At

My interface and classes

public interface INoteService {
 SomeMethod();
}

public class NoteService : INoteService {
private readonly IAuthenticationService _authenticationService;

public NoteService(IAuthenticationService authenticationService){
    _authenticationService = authenticationService;
}
//some code ...
}

public class CompanyNoteService : NoteService {

private readonly IAuthenticationService _authenticationService;

public CompanyNoteService (IAuthenticationService authenticationService) : base (authenticationService) { }
//some code...
//overriding methods
}

The controller

public class NoteController : Controller
    {

        private readonly INoteService _noteService;

        public NoteController (INoteService noteService)
        {
            _noteService= noteService;
        }
}

I want to call the methods of CompanyNoteService in the controller, using dependency injection. I registered my services like this:

services.AddScoped<IAuthenticationService, AuthenticationService>();
services.AddScoped<INoteService, CompanyNoteService>();

But I keep receiving a null value for _authenticationService. The following example works, but I want to use my overridden methods.

services.AddScoped<IAuthenticationService, AuthenticationService>();
services.AddScoped<INoteService, NoteService>();

How do I register my services in order to get things work?

1

There are 1 best solutions below

1
jbl On BEST ANSWER

I guess your problem comes from the duplicate declaration of _authenticationService.
Difficult to tell without a whole code, but I think you are setting the base class _authenticationService while you try to read the subclass _authenticationService (which remains null).
You should try something like this.

public interface INoteService {
 SomeMethod();
}

public class NoteService : INoteService {
  protected readonly IAuthenticationService _authenticationService;

  public NoteService(IAuthenticationService authenticationService){
    _authenticationService = authenticationService;
  }
//some code ...
}

public class CompanyNoteService : NoteService {
    
  public CompanyNoteService (IAuthenticationService authenticationService) : base (authenticationService) { }
  //some code...
  //overriding methods
}