AI 资讯
Decided is not done: taking stock before adding more
The first session ended at post 10. The design did not. I came back to it and, before writing a single new decision, asked the least glamorous question a solo project can ask itself: how far along is this, really, and what would it take to call it ready for someone else to review in depth? The answer was more useful than I expected, because it forced a distinction I had been blurring: a settled mechanism is not a hardened design . The fork: promote now, or hold and harden Composition was already reconciled into the binding docs. Coherence had seventeen recorded decisions covering the whole load-bearing core: binding, determinism, precedence, persona content, gender, explainability, detection, activation, the explicit accessor, and a second entity proving the abstraction generalizes. It was tempting to call that reviewable and promote it too. A: promote coherence into the binding docs now. 17 decisions, self-consistent, composition already went. Looks done. B: hold. The mechanism is settled, but the seams between features are not. Harden first, promote second. I took B. The tell was that I could not yet answer a reviewer's most obvious question, "what happens when a composed child is itself a person," without pointing at an open fork. A design you cannot stress at the seams is decided, not done. What "hardened" actually means The value of taking stock was turning a vague "almost there" into a concrete, finite list. Three passes stand between the current state and an in-depth review: 1. Cross-feature interaction pass. Where correctness bugs hide once two features exist. Composition x coherence is done (next post). Uniqueness, null-probability, and locale remain. 2. Surface-enumeration pass. Collect every public member the design has accumulated into one list to accept or cut. Public surface is locked, so this is the gate that matters most. 3. Consistency re-read. Read all the decisions straight through for contradictions and stale cross-references, the kind that creep
AI 资讯
Testing Microsoft Agent Framework Applications
This is Part 18 of my series on the Microsoft Agent Framework. You can read the original post over on lukaswalter.dev . In the previous article , we looked at observability for agents. The main idea was to make a run visible as a chain of model calls, tool calls, approvals, and workflow events. Testing starts from the same idea. An agent run is not one answer string. It is a small application flow with several boundaries: user input -> prompt and context -> model request -> model response -> tool selection -> tool arguments -> tool execution -> structured result or final answer -> routing or workflow state If the only test is an end-to-end prompt against a live model, all of those boundaries are mixed together. When the test fails, you do not know whether the problem is the prompt, the model, the tool schema, the router, the workflow, or the real dependency behind the tool. The solution is not to pretend that an LLM is deterministic. The solution is to test each boundary at the level where it is deterministic, then add a smaller number of evaluation-style tests for behavior that genuinely depends on the model. This post covers: fake model clients tool contract tests structured output tests routing tests workflow tests eval-style regression checks The examples use xUnit-style assertions, but the testing approach does not depend on xUnit. The snippets focus on the relevant testing boundary and omit some application-specific factory and workflow setup. Do not start with the live model A live model test is useful. It is also expensive, slow, sometimes flaky, and difficult to diagnose. That makes it a poor replacement for normal unit and integration tests. I use a testing pyramid for agent applications: evals realistic model and user examples application integration tests agent + tools + storage + workflow boundaries deterministic component tests fake model client, tools, schemas, routing The bottom layer should be the largest. It should catch ordinary programming mistak
AI 资讯
How I replaced if statements with a Dictionary delegate in C#
Let's say you need to implement a feature that returns a different package based on the user-provided coupon code. So you start with a model: public record Package { public int Id { get ; set ; } public string Name { get ; set ; } public double Price { get ; set ; } } And you write a function that returns a different package based on the coupon code: private static Package GetPackageFromCoupon ( string coupon ) { if ( coupon == "ABC" ) { return new Package { Id = 1 , Name = "PS5 Controller" , Price = 50.00 }; } if ( coupon == "EBC" ) { return new Package { Id = 2 , Name = "Iphone X" , Price = 200.00 }; } if ( coupon == "DDD" ) { return new Package { Id = 3 , Name = "X7 Mouse" , Price = 20.00 }; } return new Package { Id = 1000 , Name = "Soda" , Price = 1.00 }; } And invoke it from your main method: internal class Program { static void Main ( string [] args ) { var package = GetPackageFromCoupon ( "ABC" ); Console . WriteLine ( package ); Console . ReadLine (); } } Quick test Provide expected parameters and inspect the results. "ABC" => Package { Id = 1 , Name = PS5 Controller , Price = 50 } "EBC" => Package { Id = 2 , Name = Iphone X , Price = 200 } "DDD" => Package { Id = 3 , Name = X7 Mouse , Price = 20 } Works as expected. Also, if you enter something that doesn't exist: "a" => Package { Id = 1000 , Name = Soda , Price = 1 } The Problem What if you need to add more coupon codes and return different variations of the Package object? Well, it's gonna get pretty messy very soon. Quick solution - Dictionary Rather than writing every possible variation in the if block, create a dictionary where the key is the coupon code and the value is the Package: private static readonly Dictionary < string , Package > _packages = new () { [ "ABC" ] = new Package { Id = 1 , Name = "PS5 Controller" , Price = 50.00 }, [ "EBC" ] = new Package { Id = 2 , Name = "Iphone X" , Price = 200.00 }, [ "DDD" ] = new Package { Id = 3 , Name = "X7 Mouse" , Price = 20.00 }, }; The next step is to
开发者
Unity Foundational Architecture: Managing Global State
Table of Contents: Introduction Constants Singletons & Services Singleton Service Locator Introduction Every Unity developer eventually hits the exact same wall: how do I get my UI script to talk to my Game Manager without turning my codebase into a tangled web of dependencies? Managing global state is a fundamental challenge in game architecture, and the internet is full of conflicting, often dogmatic advice on how to handle it. In this article, we are going to look at some popular approaches to managing global state: Static Constants, Singletons and Service Locator. Before we start though, I encourage you to read some of my previous blog posts in this series on project scaffolding or, even more crucial to some sections in this article, the bootstrapping process . Constants Not every piece of global data needs a instance to live in, interfaces, or an initialization phase. Some data is constant and never changes at runtime (constants). These constants are usually defined with static readonly or const (at least they should be if they never change). Example: public static class MathConstants { public const float MilesToKm = 1.60934f ; } public class CharacterAnimationController : MonoBehaviour { // we must use static readonly instead of const here because we need to generate the SpeedHash from the string literal. public static readonly int SpeedHash = Animator . StringToHash ( "Speed" ); } Constants are also tied to the type they are defined in. So to keep things neat, you should only define constants where appropriate. Meaning if you have a constant for the max networked inventory slot capacity, this shouldn't be defined in a class called NetworkedConstants and instead should reside inside the class that represents the NetworkedInventory which needs this data. In fact, if this is the only class that needs this data, you can even make it private although it's perfectly fine to make it public as well if there's a need for it in other scripts as long as you are not just
AI 资讯
EF Core Is Already a Repository. Stop Wrapping It in Another One.
Open a lot of .NET projects and you'll find the repository pattern sitting on top of Entity Framework Core. IProductRepository, GetById, Add, Save, the whole set. Underneath, every method just calls the EF Core DbContext and passes the result straight back. The wrapper adds a name and nothing else. So do you need the repository pattern with EF Core? For most apps, no. EF Core already gives you one. DbSet is a repository. It already does the thing the pattern is for. The reason this keeps happening is that the repository pattern got taught alongside EF, so people assume you need one to use the other. You don't. What the Pattern Was For The repository pattern came before EF Core. It started in a time when data access meant hand-written SQL, SqlCommand, and mapping DataReader rows to objects by hand. Wrapping all of that behind an interface was worth it. It hid a real mess, and it let you swap what was underneath without the rest of the app noticing. EF Core already does that. DbContext is the unit of work. DbSet is the repository. SaveChanges() is the commit. The pattern you're adding is one the tool already gives you. What the Wrapper Actually Does Here's the shape you see in most codebases: public class ProductRepository : IProductRepository { private readonly AppDbContext _db ; public ProductRepository ( AppDbContext db ) => _db = db ; public async Task < Product ?> GetById ( int id ) => await _db . Products . FindAsync ( id ); public async Task < List < Product >> GetAll () => await _db . Products . ToListAsync (); public void Add ( Product product ) => _db . Products . Add ( product ); } Read what each method does. GetById calls FindAsync. GetAll calls ToListAsync. Add calls Add. It's a passthrough. Every line hands the call straight to EF Core and returns whatever comes back. You wrote an interface, a class, and a registration to rename methods that already existed. This is what people mean by a generic repository over EF Core, and it's the most common version y
开发者
Oscillation, Mathf.PingPong, Vector3.Lerp
When you develop a game at the beginning of your journey, you quickly notice that the environment is very static. To change that, let’s create some oscillations and move our platforms. We will use methods like Vector3.Lerp and Mathf.PingPong . using UnityEngine ; public class Oscillate : MonoBehaviour { [ SerializeField ] private Vector3 movementVector ; [ SerializeField ] private float speed ; private Vector3 _startPosition ; private Vector3 _endPosition ; private float _movementFactor ; private void Start () { _startPosition = transform . position ; _endPosition = transform . position + movementVector ; } private void Update () { _movementFactor = Mathf . PingPong ( Time . time * speed , 1f ); transform . position = Vector3 . Lerp ( _startPosition , _endPosition , _movementFactor ); } } First, we add movementVector and speed to inspector. movementVector receives the direction, and we tell it how far object must move. speed defines how fast objects move _ startPosition simply gets the starting coordinates in Start() with transform.position , and _ endPosition is the sum of the _ startPosition and movementVector . Now _ movementFactor is different. It defines the progress of the movement. Imagine it as a loading bar from 1% to 100%. In Update() method, we constantly calculate it every frame using Mathf.PingPong _movementFactor = Mathf.PingPong(Time.time * speed, 1f); So what is going on here, Mathf.PingPong does what you would imagine. Value goes back and forth. 1f is our length, so in Update() every frame _ movementFactor is getting updated from 0.0, 0.1, 0.2… up to 1.0, when the value is 1.0, it goes back to 0.0 in the same way. And since it’s in Update() this is an endless cycle. transform.position = Vector3.Lerp(_startPosition, _endPosition, _movementFactor); Now this is where magic happens. Lerp (Linear Interpolation) takes start position, end position and a “loading” bar. Why we did exactly 1f in PingPong is perfectly described in the official documentation: a
开发者
The Hidden Cost of yield in C#: What the Compiler Doesn't Tell You
Most C# developers know how to use yield return. Few understand what actually happens after compilation. If you've ever written something like this: public IEnumerable < int > GetNumbers () { yield return 1 ; yield return 2 ; yield return 3 ; } it looks almost magical. No collection. No list allocation. No iterator implementation. Yet somehow the method returns an IEnumerable. So what is really happening? The answer is one of the most elegant compiler transformations in the entire .NET ecosystem. Let's open the hood. The Illusion Most developers imagine the previous code executes like this: Call method ↓ Return 1 ↓ Pause ↓ Return 2 ↓ Pause ↓ Return 3 That isn't what happens. C# methods cannot actually pause execution. Instead, the compiler completely rewrites your method into something entirely different. The Compiler Creates a State Machine Your tiny method becomes a hidden class similar to this: private sealed class GetNumbersIterator : IEnumerable < int >, IEnumerator < int > { private int _state ; private int _current ; public bool MoveNext () { switch ( _state ) { case 0 : _current = 1 ; _state = 1 ; return true ; case 1 : _current = 2 ; _state = 2 ; return true ; case 2 : _current = 3 ; _state = - 1 ; return true ; default : return false ; } } public int Current => _current ; } Your original method no longer exists. Instead, it simply returns: return new GetNumbersIterator (); Every yield return becomes another state inside MoveNext(). Why Local Variables Don't Disappear Consider this code: IEnumerable < int > Squares () { int x = 1 ; while ( x <= 3 ) { yield return x * x ; x ++; } } After the first yield, the method "pauses." But where is x stored? Not on the stack. The original stack frame has already disappeared. Instead, the compiler promotes local variables into fields: private int _x ; The iterator object now owns every variable that must survive between iterations. This is why iterator methods can remember where they left off. Heap Allocation Happens Ma
AI 资讯
TDA (Tell Don't Ask)
Introdução A visão original de Kay para OOP não era "objetos com dados públicos que outros manipulam", era objetos que trocam mensagens e decidem sozinhos o que fazer com elas. é Tell dont ask é basicasmente um resgate dessa ideia original, porquer com o tempo muita gente passou a usar OOP como “structs com getters e setters”, pedendo o encapsulamento de verdade. Ideia Central Exemplo do Cliente e Carteira Ask Eu PERGUNTO o saldo, e EU decido o que fazer com ele if ( cliente . carteira . saldo >= 50 ) { cliente . carteira . saldo -= 50 ; } else { console . log ( "saldo insuficiente" ); } Tell Eu DIGO pro cliente pagar, e ELE decide o que faze // "Tell" — eu DIGO pro cliente pagar, e ELE decide o que fazer cliente . pagar ( 50 ); class Cliente { carteira : Carteira ; pagar ( valor : number ) { if ( this . carteira . saldo < valor ) { throw new Error ( "saldo insuficiente" ); } this . carteira . saldo -= valor ; } } Repare a diferença de responsabilidade: No "Ask", quem chama o código precisa saber a regra ("se o saldo for menor, não pode pagar") e tomar a decisão sozinho. No "Tell", o próprio objeto conhece sua regra e decide por dentro. Quem chama só diz o que quer que aconteça. Por que "perguntar" é perigoso Pensa no "Ask" espalhado pelo sistema: toda tela, todo botão, todo endpoint que cobra do cliente vai ter que copiar essa mesma verificação de saldo: if ( cliente . carteira . saldo >= valorDoCarrinho ) { ... } if ( cliente . carteira . saldo >= valorDaAssinatura ) { ... } if ( cliente . carteira . saldo >= valorDoBoleto ) { ... } Se um dia a regra mudar (por exemplo, "clientes VIP podem ficar com saldo negativo até -R$100"), você precisa caçar todos esses lugares e mudar um por um. É praticamente garantido que algum lugar vai ser esquecido — e aí seu sistema tem um bug de regra de negócio inconsistente. Com "Tell", a regra mora em um lugar só ( Cliente.pagar ). Mudar uma vez, resolve todo o sistema. Como isso conecta com Law of Demeter Os dois princípios andam
AI 资讯
What Actually Enforces Code Standards in the AI Era
If your team has ever spent 20 minutes on a pull request arguing about brace placement instead of the actual bug, welcome to the club. StyleCop was the tool to keep C# codebases from turning into everyone's personal-style soup. It did its job. But it's also old, slow, and wasn't built for a world where half your codebase might be vibe coded. The good news: .NET now ships with everything you need to enforce style natively, faster, and without an extra NuGet package. This post walks through why the old approach creaks under modern workloads, and gives you a copy-pasteable migration plan to fix it. Table of Contents The Real Cost of Style Debates Quick Refresher: What Is StyleCop? Do We Even Need Linters Now That AI Writes Code? The Problem With StyleCop: It's Slow The Modern Toolbox The 3 Layer Guardrail Strategy Step by Step Migration Guide Before and After Seeing It In Action Key Takeaways Wrapping Up The Real Cost of Style Debates Nobody has ever gotten a promotion for winning a tabs-vs-spaces argument. Yet these debates eat real time: PR bikeshedding ,reviewers nitpick spacing instead of catching actual logic bugs. Noisy git diffs ,one developer's auto-formatter touches 300 lines to fix a 3-line bug. Cognitive overhead ,jumping between services that each "feel" different slows everyone down. A linter's whole job is to make these arguments boring and automatic, so humans can focus on things that actually matter,like whether the code works . Quick Refresher: What Is StyleCop? StyleCop (and its Roslyn-based version, StyleCop.Analyzers ) is a static analysis tool that checks the visual grammar of your C# code,not bugs, not security holes, just style: Are public members documented? Are namespaces organized consistently? Do braces follow the "approved" pattern? It's not checking if your code is correct . It's checking if your code looks correct. Do We Even Need Linters Now That AI Writes Code? Short answer: yes, more than ever. AI coding assistants (Copilot, Cursor, and
AI 资讯
The Missing Row: Auto-Provisioning Derived Records Without the Race Condition
Why some records should be created by your system, not your users, and how to do it safely in .NET. A support ticket lands on your desk: "The Teams page is empty. I added a member, but no team shows up." You check the API. It's behaving exactly as written: { "items" : [], "totalCount" : 0 } Nothing is broken. And that's the problem. The system is faithfully returning nothing, because the row that the page reads from was never created. Somewhere in your design, you assumed a human would create it first. This article is about a small, recurring design decision that quietly causes empty dashboards, confused users, and "is this a bug?" tickets: who is responsible for creating derived records the user, or the system? and how to let the system do it without introducing duplicate rows or race conditions. The problem Let's use a fictional product: a collaboration tool called Loop . In Loop, the important entities are: An Organization (a paying customer). A Member (a person invited into an organization under a plan). A Team a grouping that members belong to, keyed by (OrganizationId, PlanCode) . The admin dashboard lists Teams . Each team card shows a member count. Here's the catch in the original design: creating a Member wrote a member row. Creating a Team was a separate, manual step an admin was expected to do first. If an admin invited members without first creating the matching team, the dashboard showed nothing even though the members clearly existed. From the user's point of view, they did everything right. From the system's point of view, a required row simply didn't exist. Why it matters The Team record isn't independent information. It is fully derivable from the first member invited under a plan. When one entity's existence is implied by another, forcing a human to create it manually is a design smell. It leads to: Empty states that look like outages. Users can't tell "no data" from "misconfigured." Support load. Every skipped step becomes a ticket. Silent data dr
AI 资讯
Building a Zero-Hardware Keyboard Light: My Journey with C#, WPF, and OLED Efficiency
Working late nights on server migrations and code architectures often means typing in low-light environments. While USB lamps or backlit keyboards are the standard solutions, they consume extra power and add physical clutter. I realized the ultimate light source was already directly in front of me: the monitor. With a clear vision in mind, I partnered with Google's Gemini AI to rapidly prototype and refine what became LightBar For Keyboard , a lightweight Windows application that creates a reflective light bar at the bottom of the screen to illuminate the keys. Here is how we built it using C# and WPF, tackled the Windows API to manage screen space, and optimized it for modern OLED energy consumption. The Core Challenge: Desktop Toolbars (AppBar) The simplest approach to creating a light bar is a borderless, top-most window. However, the immediate UX flaw is that maximized applications (like Chrome or Visual Studio) will either cover the bar or be partially obscured by it. To solve this, the application needed to behave like the Windows Taskbar. I implemented the native Windows Application Desktop Toolbar (AppBar) API using SHAppBarMessage from shell32.dll . Docked Mode: By registering the application as an AppBar and setting the edge to ABE_BOTTOM , Windows automatically recalculates the working area of the desktop. Result: Maximized windows are pushed upward, ensuring the light bar remains entirely visible and never covers any underlying application UI. Floating Mode: For users who need temporary access to the bottom of their screen, I added a state toggle that unregisters the AppBar and enables standard drag-and-drop window movement via MouseLeftButtonDown . Enforcing a Single Instance Because the app directly manipulates the desktop working area, launching multiple overlapping instances would cause UI glitches. To prevent this, I implemented a Mutex in App.xaml.cs to guarantee a single instance constraint. protected override void OnStartup ( StartupEventArgs e )
开发者
What MasterMemory Solves—and What It Doesn't: A Practical Guide to Static Game Data in Unity
Introduction When you build games with Unity, you eventually run into the problem of managing static game data—often called master data in Japanese game development. At first, ScriptableObject may be more than enough. If your project has a few dozen items, a few dozen enemies, and only a small number of stage definitions, ScriptableObject is convenient because you can inspect and edit everything directly in the Unity Editor. As the project grows, however, the situation changes. You may end up with tables for items, characters, skills, quests, rewards, shops, gacha pools, stages, enemy placements, progression curves, and localization text. The data is no longer edited only by programmers. Planners and game designers may need to work with it in Excel or Google Sheets. At that point, the problem is no longer just choosing a file format. You need to think about questions such as: How do you load a large amount of data quickly? How do you write ID lookups and composite-key queries safely? Should CSV or JSON be parsed directly at runtime? Is it reasonable to create a large number of Dictionaries? How do you validate references between tables? How do you debug data after converting it to binary? How do you connect the source data edited by planners to the data loaded by Unity? For the runtime loading and lookup part of that problem, one strong option is Cysharp's MasterMemory . The official README describes MasterMemory as a “Source Generator based Embedded Typed Readonly In-Memory Document Database” for .NET and Unity. In practical terms, you define your schema as C# types, a Source Generator creates a typed read-only in-memory database API, and the application loads MessagePack binary data that can be queried through type-safe methods. The official README highlights performance compared with SQLite, low allocation during queries, a small database size, and generated database structures that are type-safe and IDE-friendly. Cygames Engineers' Blog also has useful articles
AI 资讯
Building a tiny Windows tray app with .NET 9 Native AOT and raw Win32
I built CreditMeter, a small Windows tray app that shows GitHub Copilot AI-credit usage like a taxi meter. Why I built it Agentic coding makes AI usage feel invisible until you look at the bill. Constraints no WinForms no WPF no backend no telemetry no dependency-heavy architecture Tech stack C# / .NET 9 Native AOT raw Win32 / PInvoke GitHub REST API DPAPI for local PAT storage What I learned For tiny tools, architecture is also about knowing what not to add. Repo https://github.com/cdilorenzo/CreditMeter
AI 资讯
Stop writing a test-data builder for every class in .NET
If you've ever written test data by hand, you know the ritual: a PersonBuilder , an OrderBuilder , an AddressBuilder … one hand-written builder per class, each one a wall of WithX(...) methods you have to maintain forever. The Test Data Builder and Object Mother patterns are great — the boilerplate is not. XModelBuilder gives you a fluent builder for any C# class out of the box. No per-class builder required. It handles constructor parameters, init-only properties, read-only members, even private backing fields — via reflection, deterministically. Install dotnet add package XModelBuilder 30-second example You can use it fully standalone (no DI container) through a small static facade: using XModelBuilder.Default ; var order = For . Model < Order >() . With ( x => x . OrderDate , new DateTime ( 2026 , 7 , 1 )) . With ( x => x . Lines [ 0 ]. Product , "Widget" ) // deep paths + indexers just work . With ( x => x . Lines [ 0 ]. Quantity , 3 ) . Build (); No OrderBuilder , no OrderLineBuilder . The Lines[0].Product path drills into a nested collection element and sets it for you. Need a whole list? Create.Models<Order>(10) . Deterministic fakers, seeded once Random test data that changes every run is a debugging nightmare. XModelBuilder ships a seeded, dependency-free faker (and a Bogus integration if you prefer). Register it once: services . AddXModelBuilder () . AddXFaker ( seed : 12345 ); // reproducible values, every run Then let it fill in the noise while you set only what your test actually cares about: var order = xprovider . For < Order >() . With ( x => x . Id , p => p . XFake (). NewGuid ()) . With ( x => x . Customer . Name , p => p . Bogus (). Company . CompanyName ()) . With ( x => x . Lines [ 0 ]. Quantity , 3 ) . Build (); XFake().NewGuid("customer-acme") even gives you a stable GUID from a name — same key, same GUID, regardless of call order or parallelism. Deterministic by design. Build a whole list: BuildMany Need ten of something, each slightly differ
AI 资讯
10 Common Unity Networking Issues (and How to Fix Them)
Multiplayer bugs in Unity rarely look like networking bugs. They look like "the game froze," "the player teleported," or "it worked in the Editor and broke in the WebGL build." By the time you've traced it back to the actual cause, you've usually burned an afternoon. Here are 10 issues that show up constantly in Unity networking code — WebSocket-based, Socket.IO, or otherwise — with the actual root cause and the fix. A few of these come straight out of real regression tests and commit history in socketio-unity , an MIT-licensed Socket.IO v4 client for Unity. The rest are patterns you'll recognize if you've shipped a multiplayer game. 1. Reconnect wipes your room/namespace state Symptom: Connection drops for two seconds, comes back, and the player is no longer in their room/lobby/channel — even though the server never removed them. Cause: A common (bad) reconnect implementation tears down the whole client and rebuilds it from scratch — including the list of channels/namespaces the player had joined. The reconnect "succeeds" at the transport level but silently drops application-level state. Fix: Reconnect logic should preserve subscriptions across the transport reset and only re-emit join / connect for namespaces the client already had open. If you're rebuilding the socket object on every reconnect attempt, stop — reconnect the transport, keep the namespace map. // Wrong: rebuilds everything, loses namespace state void OnReconnect () => CreateFreshEngine (); // Right: reuses the existing namespace map void OnReconnect () => ReconnectEngine (); // _namespaces untouched 2. "get_gameObject can only be called from the main thread" Symptom: Random UnityException thrown from inside a network event handler, but only sometimes — usually right when the server sends something. Cause: Your WebSocket/network library delivers callbacks on its own I/O thread. Any Unity API call ( transform.position = , Instantiate , even some Debug.Log paths) from that thread throws. Fix: Never tou
AI 资讯
ASP.NET Core: Building High-Performance Web Applications and APIs
ASP.NET Core: Building High-Performance Web Applications and APIs A practical guide to ASP.NET Core — the cross-platform framework for building REST APIs, MVC applications, and backend services on .NET, covering architecture, minimal APIs, middleware, performance, and modern patterns. Table of Contents Introduction Architecture Overview Minimal APIs MVC and Controllers Middleware Pipeline Dependency Injection Configuration and Options Authentication and Authorization Performance Features Testing and Observability Quick Reference Table Conclusion Introduction ASP.NET Core is a free, open-source, cross-platform framework for building web apps, APIs, and backend services. It's a ground-up rewrite of the original ASP.NET, designed around three priorities: Performance — it's consistently one of the fastest mainstream web frameworks in independent benchmarks (e.g., TechEmpower). Modularity — you opt into only the middleware and services your app actually needs, instead of a fixed, heavyweight pipeline. Cross-platform — runs identically on Windows, Linux, and macOS, and deploys to containers, serverless, or bare metal. This guide covers the core building blocks you'll use in almost any ASP.NET Core project, from a five-line minimal API to a full MVC application with authentication and background services. 1. Architecture Overview Every ASP.NET Core app starts from a unified entry point — Program.cs — using the minimal hosting model introduced in .NET 6. var builder = WebApplication . CreateBuilder ( args ); // Register services (dependency injection container) builder . Services . AddControllers (); builder . Services . AddEndpointsApiExplorer (); builder . Services . AddSwaggerGen (); var app = builder . Build (); // Configure the HTTP request pipeline (middleware) if ( app . Environment . IsDevelopment ()) { app . UseSwagger (); app . UseSwaggerUI (); } app . UseHttpsRedirection (); app . UseAuthorization (); app . MapControllers (); app . Run (); Two phases matter here:
AI 资讯
Modern C# Features: A Deep Dive into Records, Pattern Matching, Async, and Performance
Modern C# Features: A Deep Dive into Records, Pattern Matching, Async, and Performance A practical guide to the C# language features that have reshaped how we write .NET code — records, pattern matching, async/await improvements, nullable reference types, LINQ enhancements, Span<T> , and performance optimizations. Table of Contents Introduction Records Pattern Matching Async/Await Improvements Nullable Reference Types LINQ Enhancements Span<T> and Memory<T> Performance Optimizations Quick Reference Table Conclusion Introduction C# has evolved significantly since C# 8. Each release (9, 10, 11, 12, 13) has focused on three consistent themes: Conciseness — write less boilerplate to express the same intent. Safety — catch bugs at compile time instead of runtime (especially around null ). Performance — give developers low-level control without leaving the managed, safe world of .NET. This guide walks through the features that matter most in day-to-day development, with working code examples you can drop into a dotnet run project. 1. Records Introduced in C# 9 , record types give you immutable, value-based data models with almost no ceremony. Why records exist Before records, representing an immutable data object meant hand-writing a constructor, Equals , GetHashCode , ToString , and often a With -style copy method. Records generate all of this for you. // Before: a "plain" immutable class public class PersonClass { public string FirstName { get ; } public string LastName { get ; } public PersonClass ( string firstName , string lastName ) { FirstName = firstName ; LastName = lastName ; } public override bool Equals ( object ? obj ) => obj is PersonClass p && p . FirstName == FirstName && p . LastName == LastName ; public override int GetHashCode () => HashCode . Combine ( FirstName , LastName ); public override string ToString () => $"PersonClass {{ FirstName = { FirstName }, LastName = { LastName } }} " ; } // After: the same thing as a record public record Person ( stri
AI 资讯
LINQ and ZLinq in the Unity 6 Era: Avoiding GC Allocations in Large-Scale Projects
Introduction In large-scale Unity development, GC Alloc can quietly become a real problem. At first, nothing looks wrong. But as the project grows and you add more enemies, UI, master data, events, states, notifications, logs, and other systems, small allocations that happen every frame begin to pile up. LINQ is especially convenient. var aliveEnemies = enemies . Where ( x => x . IsAlive ) . OrderBy ( x => x . DistanceToPlayer ) . ToList (); It is readable. But if this kind of code runs every frame, it can become a source of both GC Alloc and CPU overhead. Unity's official documentation also recommends reducing frequent managed heap allocations as much as possible, ideally getting close to 0 bytes per frame. https://docs.unity3d.com/2022.3/Documentation/Manual/performance-garbage-collection-best-practices.html For general GC Alloc best practices, this article refers to the Unity 2022.3 documentation, because the general guidance still applies. Unity 6-specific GC behavior is covered later using the Unity 6.0 documentation. This article assumes Unity 6.0 as the minimum Unity version and explains how to choose between regular LINQ and ZLinq in production code. Unity 6.0 uses the Roslyn C# compiler, and its C# language version is C# 9.0. However, some C# 9 features, such as init-only setters, are not supported. https://docs.unity3d.com/6000.0/Documentation/Manual/csharp-compiler.html The short version The point of this article is not to ban LINQ completely. Do not use LINQ in hot paths just because it is readable. Do not assume ZLinq solves everything just because you introduced it. Those are the two main ideas. A rough guideline looks like this: Area Guideline Editor extensions, build scripts, debug code Regular LINQ is usually fine Startup, loading, initialization LINQ can be fine, but measure when data size is large Update / LateUpdate / FixedUpdate Avoid LINQ by default Code that is not per-frame but still called frequently Consider ZLinq Code that materializes res
AI 资讯
Back to Simplicity: Why We Built CALM, a Lock-Free Single-Thread Messaging Library for .NET
Hello everyone! For many years, I have been developing equipment control software and long-term support products using .NET/C#. Based on the experiences gained through working with various development teams, I would like to talk about why I created CALM (Cooperative Async Lock-free Messaging) , an open-source library for .NET. The Magic of UI Thread + Event-Driven + async/await My journey with .NET/C# began around the days of .NET Framework 4.0. At the time, code-behind in Windows Forms was incredibly intuitive. It allowed me to join the development team and become productive in a very short period. Back then, executing time-consuming operations on a separate thread and returning the results to the UI thread via callbacks was painful and error-prone. However, the introduction of async/await in .NET Framework 4.5 completely shifted the paradigm. The SynchronizationContext magically handled thread marshaling behind the scenes, and our code became amazingly simple. "Running asynchronous operations safely on a single thread (the UI thread) via an event-driven approach" — this seamless developer experience was my starting point. Divide and Conquer, Dependency Management, and CQS As our product evolved, the codebase grew, and the development team expanded beyond a certain size. Suddenly, the software became exponentially complex. Following industry best practices, we introduced MVP and MVVM patterns to separate the UI from the business logic. We also refactored our domain models based on Domain-Driven Design (DDD) and Clean Architecture principles, alignment with the team's domain knowledge. While this helped organize the logic within individual models, it introduced a new nightmare: complex dependencies between models. We struggled heavily with initialization, especially with models that had circular or mutual dependencies. To break this web of tight coupling, we introduced a mechanism that combined the Observer pattern (inspired by Android's EventBus) with the philosoph
AI 资讯
Data-Oriented Design in C#: Why Objects Are Slowing You Down
Data-Oriented Design in C#: Why Objects Are Slowing You Down In my previous article, we talked about starving the Garbage Collector by moving away from heap-allocated class types and leaning heavily into struct , Span<T> , and ArrayPool<T> . That’s a critical first step, but it only solves half the problem. You’ve stopped the GC from pausing your app, but you might still be leaving massive amounts of CPU performance on the table. Why? Because of how your data is structured. It’s time to talk about Data-Oriented Design (DoD) . The Object-Oriented Trap We are taught from day one to model our code after the real world. If you are building a social network graph, you might write something like this: public class UserNode { public int Id { get ; set ; } public string Name { get ; set ; } public List < Edge > Connections { get ; set ; } } public class Edge { public UserNode Target { get ; set ; } public int Weight { get ; set ; } } This makes perfect logical sense. A user has connections, and those connections point to other users. But modern CPUs don't care about your logical models. A CPU only cares about reading data from memory into its L1/L2 caches as fast as possible. When a CPU reads a byte from RAM, it doesn't just read that one byte; it pulls a whole 64-byte "cache line" under the assumption that you will probably want the neighboring bytes next. When you loop through a List<UserNode> , traversing from object to object, you are jumping randomly across the heap. The CPU pulls a cache line, reads your data, and then has to go fetch a completely different block of RAM for the next node. This is called pointer chasing , and the resulting cache misses are devastating to performance. Enter Data-Oriented Design: Struct of Arrays (SoA) Data-Oriented Design says: Stop modeling the real world. Model the data the way the hardware wants to consume it. Instead of an Array of Structs (AoS) (or an array of objects), we invert the architecture to a Struct of Arrays (SoA) . If we