1

I am new to Core/Azure Functions and trying to use DI Container to add dependencies.

I want to add the class/interface dependency to DI Container:

s.AddSingleton<ITicketService>(new TicketService());
s.AddSingleton<IFoodService>(new FoodService());
s.AddSingleton<IFinancialsService>(new FinancialsService());

How do I do it for the above three classes/interfaces with them having dependance on repository classes.

s.AddSingleton<ITicketService>(new TicketService(ITicketRepository));
s.AddSingleton<IFoodService>(new FoodService(IFoodRepository));
s.AddSingleton<IFinancialsService>(
    new FinancialsService(ITicketRepository,IFoodRepository));

Here is the relevant code for those classes and interfaces:

public interface ITicketService { ... }
public interface IFoodService { ... }
public interface IFinancialsService { ... }

public class TicketService : ITicketService
{
    private readonly ITicketRepository _ticketRepo;

    public TicketService(ITicketRepository ticketRepo) => _ticketRepo = ticketRepo;
}

public class FoodService : IFoodService 
{
    private readonly IFoodRepository _foodRepo;

    public FoodService(IFoodRepository foodRepo) => _foodRepo = foodRepo;
}

public class FinancialsService : IFinancialsService
{
    private readonly ITicketRepository _ticketRepo;
    private readonly IFoodRepository _foodRepo;

    public FinancialsService(ITicketRepository ticketRepo, IFoodRepository foodRepo)
    {
        _ticketRepo = ticketRepo;
        _foodRepo = foodRepo;
    }

    public FinancialStats GetStats() ...
}

Any working example will be appreciated.

Steven
  • 166,672
  • 24
  • 332
  • 435
Sugar Bowl
  • 1,722
  • 1
  • 19
  • 24

1 Answers1

7

Use the overload where the implementation is also stated when registering the type.

s.AddSingleton<ITicketService, TicketService>();
s.AddSingleton<IFoodService, FoodService>();
s.AddSingleton<IFinancialsService, FinancialsService>();

s.AddSingleton<ITicketRepository, TicketRepository>();
s.AddSingleton<IFoodRepository, FoodRepository>();

The container will resolve the dependencies based on the registered abstractions and their implementations.

If you need to create the instance manually, then the factory delegate can be used to resolve the desired dependencies

//... assuming other dependencies already registered

s.AddSingleton<IFinancialsService>(sp => 
    new FinancialsService(
        sp.GetRequiredService<ITicketRepository>(),
        sp.GetRequiredService<IFoodRepository>()
    )
);

or simplified using ActivatorUtilities

//... assuming other dependencies already registered

s.AddSingleton<IFinancialsService>(sp => 
    ActivatorUtilities.CreateInstance<FinancialsService>(sp)
);
Nkosi
  • 235,767
  • 35
  • 427
  • 472