I am new to ASP.NET CORE API so please bare with my limited understand. I am learning about dependancy injection and I am trying to register my services in the start up class. However I noticed that one of my services has an dependancy to another service via constructor. How do I pass this within the configure services method.
Do I just ‘new up’ a the dependancy class and add it within the constructor.
Here is my implementation in the start up class:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "TestAPI", Version = "v2" });
});
services.AddSingleton<IAdminRepository>(new AdminRepository());
services.AddSingleton<IAdminService>(new AdminService(need to add dependancy here));
}
Here is implementation in my service class:
private IAdminRepository _adminRepository;
public AdminService(IAdminRepository adminRepository)
{
_adminRepository = adminRepository;
}
2
Answers
You don’t need to add the dependency explicitly, you just have to register your service with
The dependency injection framework will automatically detect the required services for your AdminService.
You don’t need to add the dependency explicitly, add a theme like this pattern.
This way, the DI framework will do it wherever needed to create a new instance.
moreover, you can use Addscope or Addtransient if you need it, for example: