서론 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...
서론 Dotnet 6 에서는 의존성 문제를 해결 하기 위해서 자체적인 Dependency Injection system 을 이용한다. (AddTransient, AddScoped, AddSingleton) 그러나 이러한 System 상의 DI만으로는 다양한 의존성 문제를 해결하기 어려울 수 있다. 그래서 이러한 문제들을 해결 하기 위한 3rd party library 들이 존재한다. (Autofac, SimpleInjector, etc ...) 이중에서 dotnet 자체적인 DI 시스템을 이용하여 customizing 된 library 인 Scrutor 에 대해서 알아보자 Scrutor Microsoft.Extensions.DependencyInjection용 어셈블리 스캔 및 확장 설치 및 Test dotnet add package Scrutor Program.cs 이동 아래 추가 사용 (ScrutorController.cs 추가) Scan and Register Rule IMyService 를 구현한 class 가 여러가지 라면 구현된 code 위치에 따라 지정되는 걸로 판단된다.. (정확하지는 않다. alphanumeric 기준은 아니다.) 즉 IMyService 를 구현한 MyService, ZMyService, AMyService 가 있고 한 파일 안에 구현되었다면 파일의 가장 마지막에 구현되어 있는 class 를 자동으로 injection 해온다. (??????????) 위와 같은 경우 자신이 원하는 class 를 가져오기 어렵기 때문에 해결하는 두가지 방법이 있다. IEnumerable<IMyService> 로 감싼 후 원하는 것을 find 한다. IMyService 를 Filtering 하기 위해 IMyService 를 확장 한다. IEnumerable<IMyService> 를 이용할 ...
서론 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
댓글
댓글 쓰기