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?
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;
}
}
11 Replies
my goal is to inject the database caller, without needing to create a new instance in the WeatherForecastController
but I need the ability to retrieve a value from the appsettings
Use a factory
Could you elaborate on that?
Any resources or documentation?
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
this may cause issues if you
This could dispose Context before
ToListAsync()
completes and it may crash stuffUnknown User•3y ago
Message Not Public
Sign In & Join Server To View
yeah specifically awaiting a Task.CompletedTask is useless and adds overhead, but don't always remove
async
and await
and return a Task directly
it may cause issuesUnknown User•3y ago
Message Not Public
Sign In & Join Server To View
to be honest, the code
await Task.CompletedTask is just a placeholder, not actually used.
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
✅ This post has been marked as answered!