.NET 솔루션의 자리
| 자리 | 들어가는 것 |
|---|
*.sln | 솔루션 파일. 프로젝트 여럿을 한 묶음으로 엮어요. 맨 위 폴더에서 dotnet build 하면 여기 적힌 프로젝트를 모두 빌드해요. |
|---|
*.csproj | 프로젝트 파일(src/이름/이름.csproj). 대상 프레임워크(net8.0), 실행 파일인지 라이브러리인지, 꾸러미와 다른 프로젝트 참조를 적어요. 같은 폴더의 .cs 파일은 따로 적지 않아도 모두 들어가요. |
|---|
Program.cs | 시작 코드. 요즘 꼴은 클래스 없이 맨 위에 코드를 적는 최상위 문이고, 예전 꼴은 static void Main 이에요. |
|---|
tests/ | 시험 프로젝트(tests/이름.Tests/). 본 프로젝트를 참조하고 xUnit 같은 시험 꾸러미를 받아 dotnet test 로 돌려요. |
|---|
appsettings.json | 웹 프로젝트의 설정 파일. 개발할 때만 사용하는 실행 설정은 Properties/launchSettings.json 이에요. 비밀값은 여기 적지 않고 사용자 비밀(user-secrets)이나 환경 변수로 넣어요. |
|---|
bin/ · obj/ | 빌드 결과와 중간 파일. 지워도 다시 생기니 git 에는 올리지 않아요. |
|---|
폴더 이름 = 네임스페이스가 관례예요. src/Acme.Hello/Services/ 안의 파일은 namespace Acme.Hello.Services; 로 시작해요.
계층 나누기
요청을 받는 곳, 규칙을 정하는 곳, 자료를 넣고 꺼내는 곳을 나눠요. 웹 API 라면 Program.cs 의 엔드포인트(MapGet) → GreetingService → IMessageRepository 차례로 부르고, 거꾸로는 부르지 않아요.
ASP.NET Core 는 의존성 주입 그릇이 처음부터 들어 있어서, builder.Services.AddSingleton<...>() 로 등록해 두면 엔드포인트 매개변수에 알맞은 객체를 넣어 줘요.
- 엔드포인트는 요청 값을 꺼내 서비스에 넘기고 응답만 만들어요.
- 서비스는 규칙을 판단해요. HTTP 가 무엇인지 몰라서 시험하기 쉬워요.
- 저장소는 interface 로 두고, 지금은 메모리 구현을 사용하다 나중에 DB 구현으로 바꿔 끼워요.
이름 짓기
네임스페이스와 프로젝트 이름은 회사.제품 꼴로 짓고, 낱말마다 첫 글자를 대문자로 써요(Acme.Hello). 시험 프로젝트는 뒤에 .Tests 를 붙여요.
- 클래스·메서드·속성은 PascalCase(
MonthlyPay), 지역 변수와 매개변수는 camelCase(teamSize), interface 는 I 로 시작(IBackup)해요. System, Console, Microsoft 같은 이름은 네임스페이스에 사용하지 않아요. Acme.Console 안에서는 Console.WriteLine 이 네임스페이스로 읽혀 오류가 나요.- 파일 하나에 공개 형식 하나, 파일 이름 = 형식 이름으로 두면 찾기 쉬워요(지켜야 하는 규칙은 아니에요).
이름보다 언제 사용하는지가 중요해요. 모두 .NET 8 에서 빌드하고 돌려 본 코드예요.
싱글톤 · 하나만 있어야 할 때
설정처럼 프로그램 전체에 하나만 있어야 하는 객체에 사용해요. 생성자를 private 으로 막고 Instance 로만 꺼내요. Lazy<T> 가 처음 꺼낼 때 한 번만, 여러 스레드에서도 안전하게 만들어요.
ASP.NET Core 에서는 직접 만들기보다 AddSingleton 으로 등록하는 편이 시험하기 쉬워요.
var a = AppSettings.Instance;var b = AppSettings.Instance;Console.WriteLine(ReferenceEquals(a, b));Console.WriteLine(a.Mode); sealed class AppSettings{ private static readonly Lazy<AppSettings> lazy = new(() => new AppSettings()); public static AppSettings Instance => lazy.Value; public string Mode { get; } = "production"; private AppSettings() { }}
실행 결과
Trueproduction
팩토리 · 무엇을 만들지 한 곳에서 정할 때
파일 확장자를 보고 알맞은 읽기 객체를 골라 주는 메서드예요. switch 식으로 짧게 적고, 모르는 확장자는 예외로 알려요. 부르는 쪽은 IReader 라는 것만 알아요.
IReader reader = ReaderFactory.For("members.csv");Console.WriteLine(string.Join(" | ", reader.Read("kim;25;seoul"))); interface IReader{ string[] Read(string line);} class CsvReader : IReader{ public string[] Read(string line) => line.Split(';');} class TsvReader : IReader{ public string[] Read(string line) => line.Split('\t');} static class ReaderFactory{ public static IReader For(string fileName) => Path.GetExtension(fileName) switch { ".csv" => new CsvReader(), ".tsv" => new TsvReader(), _ => throw new NotSupportedException(fileName), };}
실행 결과
kim | 25 | seoul
전략 · 바꿔 끼우는 계산 방법
할인처럼 방법이 여럿인 계산을 interface 로 빼고, 객체를 만들 때 골라 넣어요. 여기서는 C# 12 의 주 생성자(class Checkout(IDiscount discount))로 받는 줄을 줄였어요. 간단한 규칙은 Func<decimal, decimal> 람다로도 넣어요.
var regular = new Checkout(new NoDiscount());var member = new Checkout(new PercentOff(15));var coupon = new Checkout(new FuncDiscount(price => price - 5_000m));Console.WriteLine(regular.Pay(20_000m));Console.WriteLine(member.Pay(20_000m));Console.WriteLine(coupon.Pay(20_000m)); interface IDiscount{ decimal Apply(decimal price);} class NoDiscount : IDiscount{ public decimal Apply(decimal price) => price;} class PercentOff(int percent) : IDiscount{ public decimal Apply(decimal price) => price * (100 - percent) / 100;} class FuncDiscount(Func<decimal, decimal> rule) : IDiscount{ public decimal Apply(decimal price) => rule(price);} class Checkout(IDiscount discount){ public decimal Pay(decimal price) => discount.Apply(price);}
실행 결과
200001700015000
옵서버 · 일이 생기면 알려 주기
C# 은 이 꼴을 event 로 언어에 넣어 두었어요. 받을 쪽이 += 로 등록하고, 알리는 쪽은 Restocked?.Invoke(...) 한 줄로 모두에게 알려요. 등록한 곳이 없으면 ?. 덕분에 오류 없이 지나가요.
var shop = new Stock();shop.Restocked += item => Console.WriteLine($"Mail: {item} is back");shop.Restocked += item => Console.WriteLine($"Log: restocked {item}");shop.Restock("keyboard"); class Stock{ public event Action<string>? Restocked; public void Restock(string item) { Restocked?.Invoke(item); }}
실행 결과
Mail: keyboard is backLog: restocked keyboard
의존성 주입 · 필요한 것을 생성자로 받기
GreetingService 는 이름 저장소를 직접 new 하지 않고 생성자로 받아요. 실행할 때는 메모리 저장소를, 시험에서는 늘 같은 이름을 주는 가짜를 넣어요.
ASP.NET Core 의 builder.Services 가 이 일을 해요. 등록한 구현을 찾아 생성자에 넣어요(구조 잡기의 웹 API 시작 파일).
var real = new GreetingService(new MemoryNames());Console.WriteLine(real.Greet(1));Console.WriteLine(real.Greet(7));var test = new GreetingService(new FakeNames("Tester"));Console.WriteLine(test.Greet(1)); interface INameStore{ string? Find(int id);} class MemoryNames : INameStore{ private readonly Dictionary<int, string> names = new() { [1] = "Mina" }; public string? Find(int id) => names.GetValueOrDefault(id);} class FakeNames(string name) : INameStore{ public string? Find(int id) => name;} class GreetingService(INameStore store){ public string Greet(int id) => $"Hello, {store.Find(id) ?? "guest"}";}
실행 결과
Hello, MinaHello, guestHello, Tester