Programing Language/.Net Core
.NET CORE 6) appsettings.<env>.json 파일 다른 파일에서 사용하기(프로젝트에서 환경변수 사용)
Jude_Song
2022. 10. 24. 22:18
728x90
반응형
링크 내용을 정리하자면
1. Interface 파일, Class 파일 생성하기
public interface IMysqlConn
{
MySqlConnection GetConnection();
}
public class MysqlConn : IMysqlConn
{
private readonly IConfiguration _config;
public MysqlConn(IConfiguration config)
{
_config = config;
}
public MySqlConnection GetConnection()
{
return new MySqlConnection(_config["ConnectionStrings:DefaultConnection"]);
}
}
2. 생성한 Interface를 상속받은 Class를 만들고 Program.cs에
builder.Services.AddScoped<IMysqlConn, MysqlConn>();
와 같은 형태로 등록해준다.
3. Controller에서 사용
public class WeatherForecastController : ControllerBase
{
private readonly IMysqlConn _mysqlConn;
private readonly IConfiguration _config;
public WeatherForecastController(IConfiguration config, IMysqlConn mysqlConn)
{
_config = config;
_mysqlConn = mysqlConn;
}
[HttpGet("test",Name = "GetWeatherForecast")]
public ActionResult Get()
{
List<UserInformation> users = new List<UserInformation>();
using (MySqlConnection conn = _mysqlConn.GetConnection()) // <- 여기서 사용
{
...
...
}
return OK("");
}
}
도움 되셨다면 하단의 링크 부탁드립니다 :)
참고 링크
https://stackoverflow.com/a/52356669/11138815
.Net Core How to Access Configuration Anywhere in application
I have read through the documentation on the different ways to setup and access configuration in .Net Core 2.1 and also the options pattern that seems to be recommended (https://learn.microsoft.com...
stackoverflow.com
728x90
반응형