Hi @prof cegep
For DI with LAZY LOADING I need to call my service. BUT how to pass the expected ILogger ?
You can modify your code as blow:
public interface IFicheDataService
{
string GetData();
}
public class FicheDataService : IFicheDataService
{
private readonly HttpClient _httpClient;
private readonly ILogger<FicheDataService> _logger;
public FicheDataService(HttpClient httpClient, ILogger<FicheDataService> logger)
{
_httpClient = httpClient;
_logger = logger;
}
public string GetData()
{
_logger.LogInformation("FicheDataService is called ");
return "OK";
}
}
public class LazyLoadedServices
{
private readonly IServiceProvider _services;
private readonly ILogger<FicheDataService> _logger;
public LazyLoadedServices(IServiceProvider services, ILogger<FicheDataService> logger)
{
this._services = services;
_logger = logger;
}
public FicheDataService Create()
{
_logger.LogInformation("LazyLoadedServices is called ");
HttpClient http = this._services.GetRequiredService<HttpClient>();
return new FicheDataService(http, _logger);
}
}
Then, in the Program.cs file, register the service like this:
builder.Services.AddScoped<IFicheDataService, FicheDataService>();
builder.Services.AddScoped<LazyLoadedServices>();
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion