■ IHttpClientFactory 인터페이스를 콘솔 앱에서 사용하는 방법을 보여준다.
▶ ITestService.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System.Threading.Tasks; namespace TestProject { /// <summary> /// 테스트 서비스 인터페이스 /// </summary> public interface ITestService { //////////////////////////////////////////////////////////////////////////////////////////////////// Method #region 페이지 구하기 - GetPage() /// <summary> /// 페이지 구하기 /// </summary> /// <returns>페이지 태스크</returns> Task<string> GetPage(); #endregion } } |
▶ TestService.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; namespace TestProject { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> /// <returns>처리 결과 태스크</returns> private static async Task<int> Main() { IHostBuilder builder = new HostBuilder() .ConfigureServices ( (hostContext, services) => { services.AddHttpClient(); services.AddTransient<ITestService, TestService>(); } ) .UseConsoleLifetime(); IHost host = builder.Build(); using(IServiceScope serviceScope = host.Services.CreateScope()) { IServiceProvider serviceProvider = serviceScope.ServiceProvider; try { ITestService service = serviceProvider.GetRequiredService<ITestService>(); string pageContent = await service.GetPage(); Console.WriteLine(pageContent.Substring(0, 500)); } catch(Exception exception) { ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>(); logger.LogError(exception, "An error occurred."); } } return 0; } #endregion } } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace TestProject { /// <summary> /// 테스트 서비스 /// </summary> public class TestService : ITestService { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// HTTP 클라이언트 팩토리 /// </summary> private readonly IHttpClientFactory factory; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - TestService(factory) /// <summary> /// 생성자 /// </summary> /// <param name="factory">HTTP 클라이언트 팩토리</param> public TestService(IHttpClientFactory factory) { this.factory = factory; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 페이지 구하기 - GetPage() /// <summary> /// 페이지 구하기 /// </summary> /// <returns>페이지</returns> public async Task<string> GetPage() { HttpRequestMessage requestMessage = new HttpRequestMessage ( HttpMethod.Get, "https://www.bbc.co.uk/programmes/b006q2x0" ); HttpClient client = this.factory.CreateClient(); HttpResponseMessage responseMessage = await client.SendAsync(requestMessage); if(responseMessage.IsSuccessStatusCode) { byte[] byteArray = await responseMessage.Content.ReadAsByteArrayAsync(); return Encoding.UTF8.GetString(byteArray, 0, byteArray.Length); } else { return $"상태 코드 : {responseMessage.StatusCode}"; } } #endregion } } |
※ 패키지 설치 : Microsoft.Extensions.Hosting, Microsoft.Extensions.Http
1. 비주얼 스튜디오를 실행한다.
2. 비주얼 스튜디오에서 [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 클릭한다.
3. [패키지 관리자 콘솔]에서 아래 명령을 실행한다.
▶ 실행 명령
1 2 3 4 |
Install-Package Microsoft.Extensions.Hosting Install-Package Microsoft.Extensions.Http |