Home > other >  How to add service dependancies in ASP.NET CORE API
How to add service dependancies in ASP.NET CORE API

Time:06-25

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

CodePudding user response:

You don't need to add the dependency explicitly, you just have to register your service with

services.AddSingleton<IAdminService, AdminService>();

The dependency injection framework will automatically detect the required services for your AdminService.

CodePudding user response:

You don't need to add the dependency explicitly, add a theme like this pattern.

services.AddSingleton<IAdminRepository, AdminRepository>();
services.AddSingleton<IAdminService, AdminService>();

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:

services.Addscope<IAdminRepository, AdminRepository>();
services.Addscope<IAdminService, AdminService>();
  • Related