是的,ASP.NET Core 7 Web API 类可以使用依赖注入访问配置。下面是一个示例解决方法:
首先,确保在 Startup.cs 文件的 ConfigureServices 方法中配置依赖注入:
public void ConfigureServices(IServiceCollection services)
{
// 配置访问配置文件
services.Configure(Configuration.GetSection("AppSettings"));
// 添加其他依赖注入服务
// ...
}
接下来,创建一个 AppSettings 类来表示你的配置:
public class AppSettings
{
public string ConnectionString { get; set; }
public int MaxItemsPerPage { get; set; }
// 其他配置属性
}
然后,在你的控制器类中通过构造函数注入 AppSettings:
public class MyApiController : ControllerBase
{
private readonly AppSettings _appSettings;
public MyApiController(IOptions appSettings)
{
_appSettings = appSettings.Value;
}
[HttpGet]
public IActionResult Get()
{
// 使用配置属性
var connectionString = _appSettings.ConnectionString;
var maxItemsPerPage = _appSettings.MaxItemsPerPage;
// 处理逻辑
// ...
return Ok();
}
}
这样,你就可以在控制器类中通过 _appSettings
访问配置属性了。注意,使用 IOptions
来注入配置对象,而不是直接注入 AppSettings
。这是因为 IOptions
提供了一些额外的功能,例如自动热重载配置更改等。