'How I can inject appsettings and dbcontext to a controller?
I need to access appsettings and dbcontext on my webapi controller, I read that you can inject them on the controller constructor one or another but not both, there is a way to inject both in the controller?
I already inject appsettings in the controller on the constructor, but I don't know how also inject the dbcontext set in this line of program.cs:
builder.Services.AddDbContext<DBAuthAPI>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("AuthAPI"))
);
Thank you in advace!!!
Solution 1:[1]
I tested with my codes with .net 6 which inject appsettings and dbcontext to a controller,and it worked well:
First,I checked my appsettings:
{
"AllowedHosts": "*",
"ConnectionStrings": {
"SomeDbContext": "Server=(localdb)\\mssqllocaldb;Database=SomeDbContext-945b4cde-291a-427f-a8c0-4da5ada55b14;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Then i created class:
public class AppSettingOptions
{
public DefaultConnec ConnectionStrings { get; set; }
public string AllowedHosts { get; set; }
}
public class DefaultConnec
{
public string SomeDbContext { get; set; }
}
modified my program.cs:
builder.Services.AddDbContext<SomeDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("SomeDbContext")));
builder.Services.AddOptions();
builder.Services.Configure<AppSettingOptions>(builder.Configuration)
.AddSingleton(sp => sp.GetRequiredService<IOptions<AppSettingOptions>>().Value);
inject dbcontext and appsettings in controller:
private readonly IOptions<AppSettingOptions> _options;
private readonly SomeDbContext _context;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IOptions<AppSettingOptions> options, SomeDbContext someDbContext)
{
_logger = logger;
_options = options;
_context = someDbContext;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ruikai Feng |

