Refactor constructor to be used with DI [Answered]
Hello,
Is it possible to refactor the following constructor in order to be available for DI without the need to create a new instance?
Is it possible to refactor the following constructor in order to be available for DI without the need to create a new instance?
DatabaseCaller.cs
namespace WebApplication1.Database
{
public class DatabaseCaller : IDatabaseCaller
{
private readonly MyDbContext myDbContext;
private readonly int someValueFromConfig;
public DatabaseCaller(MyDbContext myDbContext,
int someValueFromConfig)
{
this.myDbContext = myDbContext;
this.someValueFromConfig = someValueFromConfig;
}
public async Task GetValueFromDb()
{
//query the database, code omitted
await Task.CompletedTask;
}
}
public interface IDatabaseCaller
{
Task GetValueFromDb();
}
}Program.cs//...
builder.Services.AddScoped<IDatabaseCaller, DatabaseCaller>();WeatherForecastController.cs
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly AppSettings appSettings;
private readonly DatabaseCaller databaseCaller;
private readonly MyDbContext myDbContext;
public WeatherForecastController(
IOptions<AppSettings> appSettings,
MyDbContext myDbContext)
{
this.myDbContext = myDbContext;
this.appSettings = appSettings.Value;
this.databaseCaller = new DatabaseCaller(myDbContext, this.appSettings.MyValue);
}
[HttpGet(Name = "GetWeatherForecast")]
public async Task GetAsync()
{
await databaseCaller.GetValueFromDb();
await Task.CompletedTask;
}
}