라벨이 Dependency Injection인 게시물 표시

ASPNET 6 Web Api Basic Tutorial 1 / 2 (Swagger, SeriLog, MediatR, EntityFrameworkCore, Scrutor)

이미지
작성 순서 Create Project Create Controller Add Swagger Add SeriLog Add MediatR Add EntityFramework Core Add Migration Apply Database Add Web Api  Refactoring with Extension Method 1. Create Project Create  2. Create Controller Add NewFolder to project ( Controller ) UserController.cs using Microsoft.AspNetCore.Mvc; namespace WebApiBasicTutorial.Controller { [ApiController] [Route("[controller] ")] public class UserController :ControllerBase { } } Program.cs 에 다음 코드 추가   삭제 ==>  app.MapGet( "/" , () => "Hello World!" ); 추가 ==>  builder.Services.AddControllers(); 3. Add Swagger 개발자 프롬프트에서 프로젝트 폴더로 이동  (현재 .sln 파일이 있는 폴더라면 .csproj 파일이 있는 폴더로 이동) 아래 명령 실행 dotnet add package Swashbuckle.AspNetCore Program.cs 에 다음 코드 추가 builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); app.UseSwagger(); app.UseSwaggerUI(); Properties --> launchSettings.json --> "launchUrl": "swagger",...

EF Core Query

이미지
Query (None Transaction) 모든 데이터 로드 using ( var context = new BloggingContext()) { var blogs = context.Blogs.ToList(); } 단일 엔터티 로드 using ( var context = new BloggingContext()) { var blog = context.Blogs .Single(b => b.BlogId == 1 ); } 필터링 using ( var context = new BloggingContext()) { var blogs = context.Blogs .Where(b => b.Url.Contains( "dotnet" )) .ToList(); } 예제) Select all user (모든데이터) Controller 에 다음을 추가 [ProducesResponseType(typeof(List<User>), StatusCodes.Status200OK)] [HttpGet("")] public async Task<IActionResult> GetUsers() { return Ok ( await _mediator.Send( new GetUsers())); } Command folder 에 GetUsers.cs 파일 추가 public class GetUsers : IRequest<List<User>> { } Command folder 에 GetUsersHandler.cs 파일 추가 public class GetUsersHandler : IRequestHandler<GetUsers, List<User>> { private readonly MyDbContext _dbContext; public GetUsersH...

MediatR and ...

이미지
서론 MediatR 을 이용하는 여러가지 방법에 대해 알아보자.  Request/Response IRequest 를 통해 Command 를 생성하고 IRequestHandler <CommandType, OutputType> 을 통해 handler 처리 1 public class Ping : IRequest< string > { } 1 2 3 4 5 6 7 public class PingHandler : IRequestHandler<Ping, string > { public Task< string > Handle(Ping request, CancellationToken cancellationToken) { return Task.FromResult( "Pong" ); } } 1 2 var response = await mediator.Send( new Ping()); Debug.WriteLine(response); // "Pong" 해당 event 전송 방식은 response 가 올때 까지 대기 하는 방식 이다. Response 가 없을 경우에 처리.  1 2 3 4 5 6 7 8 public class OneWay : IRequest { } public class OneWayHandlerWithBaseClass : AsyncRequestHandler<OneWay> { protected override Task Handle(OneWay request, CancellationToken cancellationToken) { // Twiddle thumbs } } Notification INotification 을 통해 Command 를 생성하고 INotificationHandler<Comma...

Mediator

이미지
 서론 Dependency Injection 을 이용하여 의존성 문제를 해결 하였으나 그것만으로는 부족할 수 있다. library 간의 강결합을 해결 하기 위한 Event mechanism 이 필요하다.  Observer, Event Bus, Event Aggregator  등     MediatR 이라는 Mediator 를 구현한 library 를 이용해 보자 설치 dotnet add package MediatR.Extensions.Microsoft.DependencyInjection 초기설정 Program.cs 로 이동 아래 추가 builder.Services.AddMediatR(AssemblyHelper.GetAllAssemblies().ToArray()); AssemblyHelper.cs 추가 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public class AssemblyHelper { public static List<Assembly> GetAllAssemblies(SearchOption searchOption = SearchOption.TopDirectoryOnly) { List<Assembly> assemblies = new List<Assembly>(); foreach ( string assemblyPath in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll" , searchOption)) { try { var assembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromA...

Dependency Injection Customization

이미지
 서론 Scan 을 통한 Scrutor 의 이용은 많은 code 를 줄이는 데 도움을 준다.  하지만 Service 를 추가 할 때마다 Scrutor 의 변경을 해야 하는 문제가 여전히 남아 있다. 이러한 문제를 해결 하기 위한 방법이 필요하다.  1. Interface 의 추가 2. Program.cs 수정 3. Service 수정 4. Controller 수정 5. Test 6. Scoped Test      IMyService 를 아래와 같이 변경 7. Singleton Test IMyService 를 아래와 같이 변경 첫 번째 호출시 두 번째 호출시 결론 이제 service 를 추가한 후 IInjectableService 인터페이스를 상속하면  scan 에 service 타입을 더 추가 하지 않고 DI 를 사용할 수 있게 되었다. 관련영상 https://www.youtube.com/watch?v=rix7_Ur1V4s