C
C#3y ago
null

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
null
nullOP3y ago
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
Kouhai
Kouhai3y ago
Use a factory
null
nullOP3y ago
Could you elaborate on that? Any resources or documentation?
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Tvde1
Tvde13y ago
this may cause issues if you
public Task<Something> GetData()
{
using var context = CreateContext();
return context.Stuff.ToListAsync();
}
public Task<Something> GetData()
{
using var context = CreateContext();
return context.Stuff.ToListAsync();
}
This could dispose Context before ToListAsync() completes and it may crash stuff
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Tvde1
Tvde13y ago
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 issues
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
null
nullOP3y ago
to be honest, the code await Task.CompletedTask is just a placeholder, not actually used.
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Accord
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server