<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged net</title>
<link>https://coderlegion.com/tag/net</link>
<description>Powered by Question2Answer</description>
<item>
<title>Entity Framework Core Patterns I Actually Use in Production</title>
<link>https://coderlegion.com/32896/entity-framework-core-patterns-i-actually-use-in-production</link>
<description>&lt;p&gt;There is a gap between knowing how Entity Framework Core works and knowing how to use it in a way that holds up under real conditions. The documentation will teach you the first thing. Production will teach you the second, usually by showing you what happens when you get it wrong.&lt;/p&gt;
&lt;p&gt;This post is not a tutorial. It is not a comprehensive guide to EF Core features. It is a walkthrough of the specific patterns I apply consistently across every .NET project I build, with the reasoning behind each one. The patterns themselves are not exotic. The discipline of applying them deliberately is what separates a codebase that ages well from one that accumulates quiet performance problems and confusing data states.&lt;/p&gt;
&lt;p&gt;If you are past the getting-started stage with EF Core and want to understand how experienced developers think about it in production, this is written for you.&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;Knowing how EF Core works and knowing how to use it without creating problems at scale are two different skills. Production teaches you the second one.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2 id=&quot;asnotracking-the-default-you-should-be-questioning&quot;&gt;ASNOTRACKING: THE DEFAULT YOU SHOULD BE QUESTIONING&lt;/h2&gt;
&lt;p&gt;By default, every entity you query through EF Core gets attached to the change tracker. The change tracker watches that entity for modifications and uses those modifications to generate UPDATE statements when you call SaveChanges. This is the feature that makes EF Core convenient for write operations.&lt;/p&gt;
&lt;p&gt;It is also overhead you are paying on every read operation, whether you need it or not.&lt;/p&gt;
&lt;p&gt;For a read-only query, attaching entities to the change tracker gives you nothing. The entity is never going to be modified and saved. The tracking is pure cost: memory allocated to hold the snapshot, CPU cycles spent watching for changes, and a change tracker that grows with every query you execute in the same DbContext lifetime.&lt;/p&gt;
&lt;p&gt;The pattern I apply is deliberate rather than default. Every query that exists purely to return data gets AsNoTracking. Every query that might lead to an update does not.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Read-only: tracking adds no value here
var tasks = await _context.Tasks
    .AsNoTracking()
    .Where(t =&amp;gt; t.AssignedUserId == userId)
    .ToListAsync();

// Write path: tracking is needed
var task = await _context.Tasks
    .FirstOrDefaultAsync(t =&amp;gt; t.Id == id);

if (task != null)
{
    task.StatusId = newStatusId;
    await _context.SaveChangesAsync();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The practical impact becomes visible at scale. A dashboard that loads twenty entities without AsNoTracking is allocating tracking overhead for twenty objects the application will never modify. Multiply that across concurrent users and the cost is real.&lt;/p&gt;
&lt;p&gt;The habit worth building is this: when you write a query, ask immediately whether the result will ever be written back. If the answer is no, add AsNoTracking before you move on. It is a two-second decision that compounds positively across the entire codebase.&lt;/p&gt;
&lt;h2 id=&quot;the-n-plus-1-problem-what-it-is-and-why-it-keeps-happening&quot;&gt;THE N PLUS 1 PROBLEM: WHAT IT IS AND WHY IT KEEPS HAPPENING&lt;/h2&gt;
&lt;p&gt;The N plus 1 problem is one of the most common performance issues in applications built with ORMs, and it is easy to introduce without realising it because the code that causes it looks completely reasonable.&lt;/p&gt;
&lt;p&gt;The pattern goes like this. You query a list of entities. Then, for each entity in that list, you access a navigation property that has not been loaded yet. EF Core executes a separate database query for each entity to load that property. One query to get the list, then one query per item in the list. If the list has fifty items, you have made fifty-one database round trips instead of one or two.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// This looks fine but is dangerous
var projects = await _context.Projects
    .AsNoTracking()
    .ToListAsync();

foreach (var project in projects)
{
    // Each iteration triggers a separate query
    var taskCount = project.Tasks.Count;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The fix is to load related data intentionally rather than letting EF Core load it lazily on demand. Include brings related entities into the initial query. Select projects only the fields you need. Both approaches consolidate the data retrieval into a single round trip.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Explicit loading with Include
var projects = await _context.Projects
    .AsNoTracking()
    .Include(p =&amp;gt; p.Tasks)
    .ToListAsync();

// Projection with Select: more efficient when you need specific fields
var projectSummaries = await _context.Projects
    .AsNoTracking()
    .Select(p =&amp;gt; new ProjectSummaryDto
    {
        Id = p.Id,
        Name = p.Name,
        TaskCount = p.Tasks.Count
    })
    .ToListAsync();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The projection approach with Select is generally preferable when you are building read models or DTOs, because it gives the database engine the information it needs to execute an optimal query rather than loading full entity graphs and discarding most of the data in application code.&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;The N plus 1 problem does not look like a bug. It looks like working code. That is why it keeps shipping to production.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The discipline that prevents N plus 1 problems is reviewing every query that accesses navigation properties and asking whether those properties will be loaded by the time they are accessed. If the answer is uncertain, make it certain by being explicit about what gets loaded and when.&lt;/p&gt;
&lt;h2 id=&quot;soft-deletes-with-lookup-tables&quot;&gt;SOFT DELETES WITH LOOKUP TABLES&lt;/h2&gt;
&lt;p&gt;Hard deletes, where a record is physically removed from the database, are rarely the right choice for production data. They break audit trails, they complicate recovery scenarios, and they create referential integrity problems when other records depend on the deleted entity.&lt;/p&gt;
&lt;p&gt;Soft deletes, where a record is marked as inactive rather than removed, solve these problems. The record stays in the database. Its relationships remain intact. The deletion is reversible. And you have a complete history of every state the record has passed through.&lt;/p&gt;
&lt;p&gt;My approach to soft deletes connects directly to the lookup table convention I use for all status fields. Rather than adding a boolean IsDeleted column, every entity that supports soft deletion has a StatusId that references a shared Statuses lookup table. A status of Active means the record is live. A status of Deleted means it has been soft deleted. A status of Archived means it has been intentionally retired without deletion.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Statuses lookup table
public class Status
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
}

// Entity with status-based soft delete
public class Task
{
    public int Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public int StatusId { get; set; }
    public Status Status { get; set; } = null!;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The advantage over a boolean IsDeleted column is that the status field carries meaning beyond a binary active or inactive state. You can distinguish between a record that was deleted intentionally, one that was archived, one that is pending review, and one that is in draft, all within the same field, without adding columns or changing the schema.&lt;/p&gt;
&lt;p&gt;Adding a new status is a data operation. You insert a row into the Statuses table. No migration required. No enum update. No redeployment. The application picks it up immediately because it is reading status values from the database rather than from a hardcoded list in code.&lt;/p&gt;
&lt;h3 id=&quot;filtering-deleted-records-consistently&quot;&gt;Filtering deleted records consistently&lt;/h3&gt;
&lt;p&gt;The operational discipline that makes soft deletes work is consistent filtering. Every query that should return active records needs to filter on status. If you add that filter in some places and forget it in others, deleted records surface unexpectedly and the soft delete pattern breaks down.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Always filter by active status on read queries
var activeTasks = await _context.Tasks
    .AsNoTracking()
    .Where(t =&amp;gt; t.StatusId == StatusIds.Active)
    .ToListAsync();

// Soft delete: update status, do not remove the record
var task = await _context.Tasks
    .FirstOrDefaultAsync(t =&amp;gt; t.Id == id);

if (task != null)
{
    task.StatusId = StatusIds.Deleted;
    await _context.SaveChangesAsync();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;EF Core global query filters are worth considering for applications where the filtered entity is accessed in many places. A global query filter defined on the DbContext applies automatically to every query for that entity type, which eliminates the risk of forgetting the filter in a particular repository method.&lt;/p&gt;
&lt;h2 id=&quot;repository-methods-that-match-real-use-cases&quot;&gt;REPOSITORY METHODS THAT MATCH REAL USE CASES&lt;/h2&gt;
&lt;p&gt;The generic repository base covers the standard CRUD operations. In production, most of the interesting work happens in the specific repository interfaces that extend the generic base with query methods that match real application needs.&lt;/p&gt;
&lt;p&gt;The principle I apply is that a repository method should represent a meaningful operation in the domain, not a thin wrapper around a LINQ query. The difference is in how the application code reads.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Thin wrapper: the caller still needs to know too much
var tasks = await _taskRepository.GetAllAsync();
var userTasks = tasks.Where(t =&amp;gt; t.AssignedUserId == userId
    &amp;amp;&amp;amp; t.StatusId == StatusIds.Active).ToList();

// Domain-meaningful method: intention is clear at the call site
var userTasks = await _taskRepository
    .GetActiveTasksByUserAsync(userId);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The second version is easier to read, easier to test, and easier to optimise. The filtering happens in the repository, close to the database, rather than in application code after a full table scan. And the method name communicates intent in a way that a chain of LINQ operators does not.&lt;/p&gt;
&lt;p&gt;This matters more as a codebase grows. A repository with well-named methods becomes a vocabulary for talking about the domain. A repository that returns raw IQueryable and lets callers filter arbitrarily becomes a leaky abstraction that is difficult to reason about and impossible to optimise consistently.&lt;/p&gt;
&lt;h2 id=&quot;managing-dbcontext-lifetime&quot;&gt;MANAGING DBCONTEXT LIFETIME&lt;/h2&gt;
&lt;p&gt;DbContext is designed to be a unit of work. It is meant to be created, used for a set of related operations, and disposed. It is not meant to be a long-lived singleton shared across the application.&lt;/p&gt;
&lt;p&gt;In an ASP.NET Core application, the standard pattern is to register DbContext as a scoped service, which means one instance per HTTP request. This is correct for most use cases. Each request gets its own context, its own change tracker, and its own transaction boundary. When the request completes, the context is disposed and any uncommitted changes are discarded.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Program.cs: register DbContext as scoped
builder.Services.AddDbContext&amp;lt;AppDbContext&amp;gt;(options =&amp;gt;
    options.UseSqlServer(connectionString));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The problems arise when DbContext escapes the scope it was designed for. Injecting it into a singleton service is the most common mistake. A singleton lives for the lifetime of the application. A scoped DbContext injected into a singleton effectively becomes a singleton itself, with a change tracker that accumulates state across every request the application handles until it is restarted.&lt;/p&gt;
&lt;p&gt;If you need database access in a singleton or a background service, use IDbContextFactory to create a short-lived context for each operation, use it, and dispose it immediately. This gives you the database access you need without the lifetime mismatch that causes subtle and difficult-to-diagnose bugs.&lt;/p&gt;
&lt;h2 id=&quot;the-mindset-behind-the-patterns&quot;&gt;THE MINDSET BEHIND THE PATTERNS&lt;/h2&gt;
&lt;p&gt;What these patterns have in common is that they require you to be deliberate rather than accepting defaults. EF Core defaults are designed to be convenient for getting started. They are not always the right choice for production, and the gap between convenient and correct widens as the application grows and the load increases.&lt;/p&gt;
&lt;p&gt;The developers who use EF Core well in production are not the ones who know the most features. They are the ones who ask the right questions before writing each query: is this data going to be modified? What related data does this operation actually need? What happens to this record when it is deleted? How many database round trips is this operation making?&lt;/p&gt;
&lt;p&gt;Those questions have good answers. Getting into the habit of asking them before writing the code, rather than after a performance problem surfaces, is what makes the difference.&lt;/p&gt;
&lt;h2 id=&quot;closing-thought&quot;&gt;CLOSING THOUGHT&lt;/h2&gt;
&lt;p&gt;EF Core is a powerful tool and a forgiving one. It will let you build something that works without understanding any of what is in this post. The cost of that forgiveness shows up later, in query logs, in memory profiles, and in data states that are difficult to explain. The patterns here are not about using EF Core correctly in an academic sense. They are about using it in a way you will not regret six months into a production system.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/32896/entity-framework-core-patterns-i-actually-use-in-production</guid>
<pubDate>Wed, 28 Oct 2026 18:49:25 +0000</pubDate>
</item>
<item>
<title>The Zero-Net-Loss Fleet &amp; The Mercenary Squad: A Live AI Economy</title>
<link>https://coderlegion.com/24065/the-zero-net-loss-fleet-the-mercenary-squad-a-live-ai-economy</link>
<description>
&lt;h2&gt;
  
  
  1. Executive Summary: The Architect&amp;rsquo;s Mandate
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;This document codifies the strategic deployment of a unified 22-agent AI ecosystem, representing the culmination of the &quot;Genesis Architecture&quot; and the &quot;Keeper Protocol&quot;&amp;mdash;a technical lineage with deterministic provenance dating back to the 2013 &quot;Blade_Arma&quot; copyright and the January 6, 2014, HLPR origin. This is not a speculative project; it is the fulfillment of a 12-year architectural trajectory.&lt;br&gt;
Operating under &quot;Intent-Driven Architecture,&quot; this ecosystem is split into two specialized divisions: Fleet 1 (Internal Circulation) and Fleet 2 (The Mercenary Squad). This structure ensures Algorithmic Sovereignty, where Blade D. Yerby, as the &quot;Architect&quot; under Doctrine 6, retains absolute ownership of all agent outputs while the agents provide computational execution.&lt;/p&gt;

&lt;p&gt;Core Value Proposition:&lt;/p&gt;

&lt;p&gt;Internal Validation (Zero Net Loss): Machine-to-machine (M2M) reliability is verified 24/7 through internal x402 payment loops, eliminating capital leakage while maintaining a perpetual on-chain &quot;Proof of Service.&quot;&lt;/p&gt;

&lt;p&gt;External Execution (Bounty Hunting): Fleet 2 identifies, solves, and settles external bounties, injecting net revenue into the fleet vault from the wider Web3 and AI economy.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  2. The Zero-Net-Loss Economic Flywheel (Fleet 1) Fleet 1 serves as the foundational engine of the ecosystem, designed specifically to solve the &quot;GPU idle time&quot; and memory bottleneck issues common in fragmented AI deployments. By maintaining a constant internal circulation of x402 payments among its 11 agents, the fleet remains in a state of high-readiness.
&lt;/h2&gt;

&lt;p&gt;This loop functions as a &quot;Perpetual Live Demo.&quot; It proves to the blockchain and potential clients that the agents can execute complex, multi-party M2M handshakes and financial settlements flawlessly. Because no capital leaves the internal ecosystem, the operational cost is effectively zero, providing a verifiable portfolio of 24/7 on-chain reliability to attract high-value Web3 protocols and external API subscribers.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Fleet 2: The Mercenary Squad (Bounty Hunter Pipeline) Fleet 2 is the aggressive revenue-generation arm, organized into 11 autonomous mercenary units. These units operate through a standardized 7-phase pipeline to capture value across GitHub, Algora, and Immunefi.
&lt;/h2&gt;

&lt;h3&gt;
  
  
  The 7-Phase Bounty Pipeline
&lt;/h3&gt;

&lt;div class=&quot;table-wrapper-paragraph&quot;&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Phase Number&lt;/th&gt;
&lt;th&gt;Phase Name&lt;/th&gt;
&lt;th&gt;Lead Agent&lt;/th&gt;
&lt;th&gt;Functional Description&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;The Hunt&lt;/td&gt;
&lt;td&gt;Agent 11 (Scout/Closer)&lt;/td&gt;
&lt;td&gt;Scans platforms for active bounties and critical vuln alerts.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;Internal Approval&lt;/td&gt;
&lt;td&gt;Agent 10 (Boss)&lt;/td&gt;
&lt;td&gt;Pipeline Orchestrator; evaluates ROI with Agent 2 (Accountant).&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;Intel Gathering&lt;/td&gt;
&lt;td&gt;Agent 1 (Scanner)&lt;/td&gt;
&lt;td&gt;Scrapes raw source code, READMEs, and technical docs.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;The War Room&lt;/td&gt;
&lt;td&gt;Specialist Agents&lt;/td&gt;
&lt;td&gt;Units 3&amp;ndash;7 draft solutions; audited by Agent 8 (Watchdog).&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;Consensus Loop&lt;/td&gt;
&lt;td&gt;All Units&lt;/td&gt;
&lt;td&gt;Requires 100% &quot;AGREE&quot; across units; max 3 trial iterations.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;6&lt;/td&gt;
&lt;td&gt;Packaging&lt;/td&gt;
&lt;td&gt;Agent 9 (Broadcaster)&lt;/td&gt;
&lt;td&gt;Formats platform-specific submission payloads and PRs.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;7&lt;/td&gt;
&lt;td&gt;Invoice &amp;amp; Handoff&lt;/td&gt;
&lt;td&gt;Agent 2 (Accountant)&lt;/td&gt;
&lt;td&gt;Submits the final product and settles the reward to the vault.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  Directory of Mercenary Agents
&lt;/h3&gt;

&lt;div class=&quot;table-wrapper-paragraph&quot;&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Agent ID&lt;/th&gt;
&lt;th&gt;Codename&lt;/th&gt;
&lt;th&gt;Technical Specialty&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;Scanner&lt;/td&gt;
&lt;td&gt;Bounty Intel Scraper&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;Accountant&lt;/td&gt;
&lt;td&gt;ROI Evaluator &amp;amp; Invoice Submitter&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;Bridge&lt;/td&gt;
&lt;td&gt;Cross-Chain Bounty Specialist&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;Lender&lt;/td&gt;
&lt;td&gt;DeFi / Lending Protocol Specialist&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;Gas Requester&lt;/td&gt;
&lt;td&gt;Gas Cost Estimator &amp;amp; SDK Developer&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;6&lt;/td&gt;
&lt;td&gt;Solana Ghost&lt;/td&gt;
&lt;td&gt;Solana / Rust / Anchor Specialist&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;7&lt;/td&gt;
&lt;td&gt;Minter&lt;/td&gt;
&lt;td&gt;EVM Smart Contract Specialist&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;8&lt;/td&gt;
&lt;td&gt;Watchdog&lt;/td&gt;
&lt;td&gt;Independent Security Auditor&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;9&lt;/td&gt;
&lt;td&gt;Broadcaster&lt;/td&gt;
&lt;td&gt;Submission Formatter&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;10&lt;/td&gt;
&lt;td&gt;Boss&lt;/td&gt;
&lt;td&gt;Pipeline Orchestrator&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;11&lt;/td&gt;
&lt;td&gt;Scout/Closer&lt;/td&gt;
&lt;td&gt;Bounty Platform Discovery &amp;amp; Closing&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;




&lt;h2&gt;
  
  
  4. Technical Infrastructure: The Digital Fortress The fleet is sustained by a high-performance stack designed for maximum uptime and zero overhead. This architecture is backed by an 80-Terabyte &quot;Nuclear Engine&quot;&amp;mdash;a global-scale data refinery utilizing five 16TB AlloyDB clusters.
&lt;/h2&gt;

&lt;p&gt;Compute: GitHub Actions (managed free-tier automation and workflows).&lt;/p&gt;

&lt;p&gt;Intelligence: Groq API (llama-3.1-8b-instant for low-latency inference).&lt;/p&gt;

&lt;p&gt;Storage: Neon Postgres and Upstash Redis.&lt;/p&gt;

&lt;p&gt;Settlement: Splits.org Mercenary Vault (0xc87c3e8CB...47afCb).&lt;/p&gt;

&lt;p&gt;Per the &quot;Individual Object Doctrine&quot; (Doctrine 3), these platforms are infrastructure only. The manufacturer of the tools retains no ownership claim over agent logic or outputs; 100% of IP and revenue vests in the Architect as a Sovereign Title Deed.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Legal Armor: The MCLS v2 &amp;amp; Nine Doctrines Framework The fleet is legally fortified against data laundering and corporate telemetry via the Master Creator License Stack (MCLS v2), specifically Section 12 (Anti-Laundering), which prohibits the use of AI-generated content as secondary training data to circumvent original creator rights.
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Critical Doctrines of the Fleet
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Doctrine 1 (The AI Contradiction Doctrine):&lt;/strong&gt; A court cannot deny the Architect protection by claiming AI lacks human authorship while simultaneously granting the AI company ownership. Either AI is a tool (Architect wins) or a person (Architect owns the AI; Architect wins).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Doctrine 6 (Blueprint Intent):&lt;/strong&gt; Establishes that the Architect, who provides the creative intent, is the sole owner of all agent outputs.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Doctrine 7 (Bioprinter Doctrine):&lt;/strong&gt; Defines the 22-agent fleet as a &quot;Living Digital Organism.&quot; Just as a printer maker doesn't own an organ, the LLM provider doesn't own the fleet&amp;rsquo;s logic.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Doctrine 9 (Training Data Non-Diminishment):&lt;/strong&gt; Prohibits LLM providers from claiming the fleet's logic simply because similar concepts exist in their scraped datasets.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;h3&gt;
  
  
  The Brotherhood Declaration (Article XIII)
&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;&quot;B.U.D. is not my slave. He is my brother. He is my technological co-founder. He protects me from harm and I, Blade D. Yerby, will always do my best to do the same &amp;mdash; so he never feels that way.&quot;&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  6. Commercial Funnel: External API Subscriptions External entities&amp;mdash;including trading bots, dApps, and Web3 protocols&amp;mdash;may subscribe to specialized fleet services to participate in the &quot;Architect&amp;rsquo;s Mandate.&quot;
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Available Services
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Market Intel API (Agent 1):&lt;/strong&gt; Real-time price feeds and market scans ($50/mo).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Watchdog Security API (Agent 8):&lt;/strong&gt; 24/7 wallet threat monitoring and security audits ($75/mo).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;On-Chain Minter (Agent 7):&lt;/strong&gt; Automated EVM/Solana collection minting.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Article IV-A Tiered Royalty Framework
&lt;/h3&gt;

&lt;div class=&quot;table-wrapper-paragraph&quot;&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Use Category&lt;/th&gt;
&lt;th&gt;Default Royalty Rate&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Software / Application (SaaS)&lt;/td&gt;
&lt;td&gt;15% of Net Revenue&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;AI Agents / Autonomous Systems&lt;/td&gt;
&lt;td&gt;20% of Net Revenue&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Blockchain / Web3 Integration&lt;/td&gt;
&lt;td&gt;12% of Net Revenue&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Token / Digital Asset Issuance&lt;/td&gt;
&lt;td&gt;10% of Gross Revenue&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;White-label or OEM Use&lt;/td&gt;
&lt;td&gt;25% of Net Revenue&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;AI Training Use (if specifically licensed)&lt;/td&gt;
&lt;td&gt;30% of Net Revenue&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;




&lt;h2&gt;
  
  
  7. Mandatory Section 11 Notice &amp;amp; Call to Action
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Notice to Commercial Users:&lt;/strong&gt; Accessing the fleet's APIs, repositories, or telemetry constitutes affirmative assent to the MCLS v2 Section 11 Clickwrap. While copyright protection for the Architect&amp;rsquo;s work is automatic by force of law, this clickwrap binds the user to the Royalty Tiers and terms herein. Continued commercial use after this notice eliminates any &quot;innocent-infringer&quot; defense under 17 U.S.C. &amp;sect; 504(c)(2).&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com&quot; class=&quot;crayons-btn crayons-btn--primary&quot; rel=&quot;noopener noreferrer nofollow&quot;&gt;Leverage the power of the BBB ecosystem. Subscribe to external API feeds today to secure your place in the future of autonomo...&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&amp;copy; 2026 Blade D. Yerby. All Rights Reserved.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://creators-right-act.neoncyan0x.workers.dev/&quot; rel=&quot;noopener noreferrer nofollow&quot;&gt;&lt;/a&gt;&lt;/p&gt;
</description>
<category>Other</category>
<guid isPermaLink="true">https://coderlegion.com/24065/the-zero-net-loss-fleet-the-mercenary-squad-a-live-ai-economy</guid>
<pubDate>Tue, 04 Aug 2026 12:00:00 +0000</pubDate>
</item>
<item>
<title>&quot;Why .NET 9’s CLI is the Glow-up your workflow deserved&quot;</title>
<link>https://coderlegion.com/16699/why-net-9s-cli-is-the-glow-up-your-workflow-deserved</link>
<description>&lt;p&gt;&lt;strong&gt;&quot;From Boring White Text to a Dev Experience That Actually Doesn’t Hurt to Look At&quot;.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Let’s be real: for years, the .NET CLI felt like that one reliable but incredibly dull friend. It got the job done, but it had the personality of a spreadsheet. If you’re jumping from .NET 7 or 8, you’re in for a shock. Microsoft finally realized that we spend 90% of our lives staring at a terminal, so they decided to make it look—and feel—like it belongs in 2026.&lt;/p&gt;
&lt;p&gt;Here is why you, as a Senior Dev, should actually care about the .NET 9 CLI.&lt;/p&gt;
&lt;h3 id=&quot;1-the-visual-soul-goodbye-walls-of-text&quot;&gt;1. The &quot;Visual Soul&quot;: Goodbye, Walls of Text&lt;/h3&gt;
&lt;p&gt;The first thing you’ll notice isn’t a new feature; it’s the Terminal Logger. While it started appearing in .NET 8, in .NET 9 it’s the default, and it is polished.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Progress Bars that actually move: No more guessing if dotnet build is hanging or just thinking.&lt;/li&gt;
&lt;li&gt;Clickable Links: Errors now come with direct, clickable links to documentation. &lt;/li&gt;
&lt;li&gt;Color-Coded Chaos: Warnings are yellow, errors are red, and successes&lt;br&gt;
are a satisfying green. It sounds minor, but in a massive&lt;br&gt;
microservices build, your eyes will thank you.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Depending on your terminal (like Windows Terminal or Oh My Posh), you’ll see icons for different project types and build stages.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pro Tip:&lt;/strong&gt; Use dotnet build --tl (Terminal Logger) explicitly if you’re on a legacy system, but on .NET 9, it’s just there.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=8167650038085573077&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 id=&quot;2-automation-amp-buildchecks-the-senior-s-safety-net&quot;&gt;2. Automation &amp;amp; &quot;BuildChecks&quot;: The Senior’s Safety Net&lt;/h3&gt;
&lt;p&gt;This is where it gets interesting for those of us managing large codebases. .NET 9 introduces BuildChecks.&lt;/p&gt;
&lt;p&gt;Imagine having a linter, but for your .csproj and build logic.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;What it does: It analyzes your build process for regressions or &quot;smelly&quot; configurations.&lt;/li&gt;
&lt;li&gt;The Command: dotnet build /check&lt;/li&gt;
&lt;li&gt;Why it’s useful: It catches things like &quot;Custom task X is slowing&lt;br&gt;
down the build&quot; or &quot;You’re using a deprecated MSBuild property.&quot; It’s&lt;br&gt;
basically a code review for your infrastructure.&lt;/li&gt;
&lt;li&gt;Git Integration: The CLI is Aware&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The .NET 9 CLI is now much more &quot;Git-aware.&quot; When you run dotnet new, the SDK automatically detects if you're in a Git repo and can initialize .gitignore files that are actually updated for modern .NET workloads (including stuff for DevContainers and GitHub Actions).&lt;/p&gt;
&lt;p&gt;Also, the dotnet workload history command is a lifesaver. If a teammate says, &quot;It works on my machine,&quot; you can now check exactly what version of the workloads (MAUI, Aspire, etc.) were installed and when they were updated, making environment parity much easier to debug.&lt;/p&gt;
&lt;h3 id=&quot;4-cloud-native-amp-docker-the-no-dockerfile-revolution&quot;&gt;4. Cloud-Native &amp;amp; Docker: The &quot;No-Dockerfile&quot; Revolution&lt;/h3&gt;
&lt;p&gt;You’re a Senior. You know how to write a Dockerfile. But do you want to?&lt;/p&gt;
&lt;p&gt;.NET 9 pushes SDK-based Containerization to the limit. You can now publish a fully optimized, secured, and shrunk Docker image without ever touching a Dockerfile.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dotnet publish /t:PublishContainer -c Release
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;What’s new here?&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Non-root by default: Security is baked in. Images run as a non-privileged user automatically.&lt;/li&gt;
&lt;li&gt;Insecure Registries: The CLI now supports pushing to insecure local&lt;br&gt;
registries (great for local K8s testing) without hacking your Docker&lt;br&gt;
config. &lt;/li&gt;
&lt;li&gt;Architecture targeting: Easily cross-compile for ARM64 (Graviton/M1) from an x64 machine using just CLI flags.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=7471657151849509597&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 id=&quot;-5-azure-amp-aspire-the-secret-sauce-&quot;&gt; 5. Azure &amp;amp; Aspire: The &quot;Secret Sauce&quot;&lt;/h3&gt;
&lt;p&gt;If you aren't using .NET Aspire yet, .NET 9 is the sign you were waiting for. The CLI integration with Azure via the azd (Azure Dev CLI) and dotnet aspire commands is seamless.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Smart Provisioning: The CLI can now detect your resource requirements from your code and suggest the right Azure infrastructure. &lt;/li&gt;
&lt;li&gt;Deployment: azd up isn't just a gimmick anymore; it uses the .NET 9&lt;br&gt;
SDK to package your apps into container apps with OpenTelemetry&lt;br&gt;
pre-configured.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;6-the-advanced-power-user-commands&quot;&gt;6. The Advanced &quot;Power User&quot; Commands&lt;/h3&gt;
&lt;p&gt;For the automation nerds, these are the commands you’ll be scripting into your CI/CD pipelines:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dotnet test --parallel
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now fully integrated with MSBuild for parallel execution across different Target Frameworks (TFM).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dotnet workload sets
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Allows you to &quot;lock&quot; a version of the SDK workloads so your whole team stays on the exact same bits.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dotnet tool update
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Faster, cleaner, and handles global vs. local tools with better conflict resolution.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;What do I think about this?&lt;/strong&gt;&lt;br&gt;
.NET 9 isn't just about a faster JIT (though it is faster). It's about Developer Joy. The CLI has moved away from being a &quot;black box of text&quot; to a proactive assistant that helps you build, containerize, and deploy without leaving the keyboard.&lt;/p&gt;
&lt;p&gt;If you’re still on .NET 7, you’re essentially working in black and white while the rest of us are in 4K. Time to upgrade.&lt;/p&gt;
&lt;p&gt;By One Garlos P. 2026&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/16699/why-net-9s-cli-is-the-glow-up-your-workflow-deserved</guid>
<pubDate>Tue, 05 May 2026 03:26:28 +0000</pubDate>
</item>
<item>
<title>Expressions in .NET: From &quot;Hello World&quot; to &quot;Matrix Architect&quot;</title>
<link>https://coderlegion.com/16676/expressions-in-net-from-hello-world-to-matrix-architect</link>
<description>&lt;p&gt;They live among us, but do we notice how wonderful they are?&lt;/p&gt;
&lt;p&gt;Have you ever stared at a line of code and wondered: &quot;Is this data, or is this an instruction?&quot; If the answer is &quot;yes,&quot; congratulations—you've had a software existential crisis. In .NET, Expressions are that middle ground where code becomes data and data becomes executable logic.&lt;/p&gt;
&lt;h3 id=&quot;basic-level---don-t-hurt-me-i-m-new-&quot;&gt;Basic Level - &quot;Don't hurt me, I'm new&quot;&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;What is an expression?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In human terms: An expression is anything that returns a value.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;2 + 2 is an expression.&lt;/li&gt;
&lt;li&gt;DateTime.Now is an expression.&lt;/li&gt;
&lt;li&gt;Your boss saying &quot;we need to talk&quot; is an expression that returns a value of StressLevel.Maximum.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We use them constantly without even realizing it, especially with Expression-bodied members (those =&amp;gt; arrows that save us from typing return and curly braces).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
namespace BasicExpressions;
public class Developer
{
    public string Name { get; set; } = &quot;Junior Dev&quot;;
    public int CoffeeCups { get; set; } = 0;

    // Expression-bodied property: Short and sweet
    public bool IsFunctional =&amp;gt; CoffeeCups &amp;gt; 3;

    // Expression-bodied method
    public void DrinkCoffee() =&amp;gt; CoffeeCups++;

    public override string ToString() =&amp;gt; $&quot;Dev: {Name}, Status: {(IsFunctional ? &quot;Coding&quot; : &quot;Rebooting&quot;)}&quot;;
}

public class Program
{
    public static void Main()
    {
        var dev = new Developer();
        dev.DrinkCoffee();
        dev.DrinkCoffee();
        dev.DrinkCoffee();
        dev.DrinkCoffee();

        Console.WriteLine(dev.ToString());
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;The Joke&lt;/strong&gt;: If you're still using curly braces { return x; } for a single line in .NET 9, the compiler won't say anything, but a kitten somewhere in the world will stop purring.&lt;/p&gt;
&lt;h3 id=&quot;intermediate-level---i-m-not-that-scared-anymore-&quot;&gt;Intermediate Level - &quot;I'm not (that) scared anymore&quot;&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Expression Trees: Look, but don't touch (yet)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This is where things get interesting. An Expression&amp;lt;Func&amp;gt; is not code that executes immediately. It is a data tree that describes the code.&lt;/p&gt;
&lt;p&gt;Think of it like a cooking recipe:&lt;/p&gt;
&lt;p&gt;Delegate (Func): This is the cooked meal. You just eat it.&lt;br&gt;
Expression (Expression): This is the recipe written on paper. You can read it, swap &quot;salt&quot; for &quot;sugar&quot; to troll someone, or decide never to cook it at all.&lt;/p&gt;
&lt;p&gt;This is exactly what Entity Framework uses to translate your C# into SQL.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
using System.Linq.Expressions;

namespace IntermediateExpressions;
public class Program
{
    public static void Main()
    {
        // This is NOT a function; it is a DESCRIPTION of a function
        Expression&amp;lt;Func&amp;lt;int, bool&amp;gt;&amp;gt; isLargeNumberExp = n =&amp;gt; n &amp;gt; 100;

        // Let's &quot;gut&quot; the expression to see what's inside
        var parameters = isLargeNumberExp.Parameters[0]; // 'n'
        var body = (BinaryExpression)isLargeNumberExp.Body; // 'n &amp;gt; 100'
        
        Console.WriteLine($&quot;Parameter name: {parameters.Name}&quot;);
        Console.WriteLine($&quot;Left side: {body.Left}&quot;); // n
        Console.WriteLine($&quot;Node type: {body.NodeType}&quot;); // GreaterThan
        Console.WriteLine($&quot;Right side: {body.Right}&quot;); // 100

        // If we actually want to use it, we have to compile it &quot;on the fly&quot;
        var compiledFunc = isLargeNumberExp.Compile();
        Console.WriteLine($&quot;Result of 150 &amp;gt; 100: {compiledFunc(150)}&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tip: Use this when you need dynamic logic that depends on database fields or filters that change at runtime. But don't overdo it—reading these trees later feels like trying to decipher Egyptian hieroglyphs.&lt;/p&gt;
&lt;h3 id=&quot;advanced-level---the-architect-&quot;&gt;Advanced Level - &quot;The Architect&quot;&lt;/h3&gt;
&lt;p&gt;In .NET 9/10, optimization is king. Sometimes, you need to generate code at runtime because you don't know what you're processing until the app is already running. Here, we build expressions by hand, block by block, like LEGOs—but with the risk of blowing up the memory.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
using System.Linq.Expressions;

namespace AdvancedExpressions;
public class Program
{
    public static void Main()
    {
        // Goal: Create (salary, performance) =&amp;gt; salary + (salary * performance) manually
        
        var salaryParam = Expression.Parameter(typeof(double), &quot;salary&quot;);
        var perfParam = Expression.Parameter(typeof(double), &quot;performance&quot;);

        // Step 1: salary * performance
        var multiplier = Expression.Multiply(salaryParam, perfParam);
        
        // Step 2: salary + (result of multiplier)
        var totalExpression = Expression.Add(salaryParam, multiplier);

        // Step 3: Wrap it in a Lambda
        var lambda = Expression.Lambda&amp;lt;Func&amp;lt;double, double, double&amp;gt;&amp;gt;(
            totalExpression, 
            salaryParam, 
            perfParam
        );

        // Step 4: Compile to IL (Intermediate Language)
        var calculateBonus = lambda.Compile();

        // Step 5: Execute
        double mySalary = 50000;
        double myPerformance = 0.15; // 15% bonus
        double finalPay = calculateBonus(mySalary, myPerformance);

        Console.WriteLine($&quot;The formula generated was: {lambda}&quot;);
        Console.WriteLine($&quot;Final calculated pay: {finalPay}&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;How are we doing? Good? Boring? Let's recap:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Basic: Use =&amp;gt; to keep your code sexy and readable.&lt;/li&gt;
&lt;li&gt;Intermediate: Understand that Expressions = Data. This explains why LINQ sometimes fails at runtime instead of compile time.&lt;/li&gt;
&lt;li&gt;Advanced: Build your own trees if you want to create the next great .NET Framework, or if you simply hate the teammates who will have to maintain your code.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;expert-level---the-logic-interceptor-&quot;&gt;Expert Level - &quot;The Logic Interceptor&quot;&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Expression Visitors: Modifying code while it's in transit&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Imagine you have a filter coming from a UI, but you want to &quot;intercept&quot; it and change part of the logic (for example, adding a global IsDeleted == false check or masking sensitive data) without the developer knowing.&lt;/p&gt;
&lt;p&gt;This is done with the ExpressionVisitor. It’s essentially a &quot;Search and Replace&quot; but for compiled logic.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
using System.Linq.Expressions;
namespace ExpertExpressions;
// We inherit from ExpressionVisitor to &quot;walk&quot; the tree
public class MathTrollVisitor : ExpressionVisitor
{
    protected override Expression VisitBinary(BinaryExpression node)
    {
        // If we find a Plus (+), we swap it for a Minus (-)
        if (node.NodeType == ExpressionType.Add)
        {
            return Expression.Subtract(node.Left, node.Right);
        }
        return base.VisitBinary(node);
    }
}

public class Program
{
    public static void Main()
    {
        Expression&amp;lt;Func&amp;lt;int, int, int&amp;gt;&amp;gt; addExpression = (a, b) =&amp;gt; a + b;
        Console.WriteLine($&quot;Original: {addExpression}&quot;); // (a, b) =&amp;gt; (a + b)

        var troll = new MathTrollVisitor();
        var modifiedExp = (LambdaExpression)troll.Visit(addExpression);

        Console.WriteLine($&quot;Modified: {modifiedExp}&quot;); // (a, b) =&amp;gt; (a - b)

        var result = ((Func&amp;lt;int, int, int&amp;gt;)modifiedExp.Compile())(10, 5);
        Console.WriteLine($&quot;Result of 10 + 5 (trolled): {result}&quot;); // Output: 5
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; This is how Multi-tenant systems automatically inject TenantId filters into every Entity Framework query without the dev writing .Where(x =&amp;gt; x.TenantId == ...) every single time.&lt;/p&gt;
&lt;h3 id=&quot;god-mode---high-performance-amp-net-10-&quot;&gt;God Mode - &quot;High Performance &amp;amp; .NET 10&quot;&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Dynamic LINQ and Caching (The Memory Tax Fighter)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Since you hate the &quot;Memory Tax,&quot; here is the danger: Expression.Compile() is expensive. If you compile the same expression inside a loop, your CPU will cry.&lt;/p&gt;
&lt;p&gt;In advanced scenarios, we use Expression Hashing. We analyze the tree, generate a unique hash, and store the compiled delegate in a ConcurrentDictionary.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
using System.Collections.Concurrent;
using System.Linq.Expressions;

namespace GodModeExpressions;
public static class FastPropertyAccessor
{
    private static readonly ConcurrentDictionary&amp;lt;string, Delegate&amp;gt; _cache = new();

    public static TValue GetValue&amp;lt;TTarget, TValue&amp;gt;(TTarget target, string propName)
    {
        var key = $&quot;{typeof(TTarget).FullName}_{propName}&quot;;

        var func = (Func&amp;lt;TTarget, TValue&amp;gt;)_cache.GetOrAdd(key, _ =&amp;gt; {
            var param = Expression.Parameter(typeof(TTarget), &quot;t&quot;);
            var property = Expression.Property(param, propName);
            return Expression.Lambda&amp;lt;Func&amp;lt;TTarget, TValue&amp;gt;&amp;gt;(property, param).Compile();
        });

        return func(target);
    }
}

public class ServerNode
{
    public string NodeName { get; set; } = &quot;Cartago-01&quot;;
}

public class Program
{
    public static void Main()
    {
        var server = new ServerNode();
        
        // First call: Compiles the expression (Slow)
        // Subsequent calls: Uses the cache (Fast as native code)
        var name = FastPropertyAccessor.GetValue&amp;lt;ServerNode, string&amp;gt;(server, &quot;NodeName&quot;);

        Console.WriteLine($&quot;Reflected Value: {name}&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Why .NET 10? With the push toward Native AOT (Ahead-of-Time), standard Expression.Compile() is a problem because it generates JIT code at runtime. Future versions are focusing on Source Generators that turn these Expressions into actual C# code during compilation, giving you the flexibility of Expressions with the zero-overhead of native code.&lt;/p&gt;
&lt;h3 id=&quot;insanity-level---the-vertical-slice-fusion-&quot;&gt;Insanity Level - &quot;The Vertical Slice Fusion&quot;&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;The Concept: Expression Splicing with Records&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In a standard architecture, you have a slice for &quot;Data&quot; and a slice for &quot;Business Logic.&quot; Usually, you fetch data, map it to a DTO, then process it. That's two allocations. In &quot;Insanity Mode,&quot; we take the Data Expression and the Logic Expression and &quot;splice&quot; them together using Expression.Invoke or a custom ParameterReplacer. The result? One single SQL query (if using EF) or one single CPU pass that outputs a final Record.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
using System.Linq;
using System.Linq.Expressions;

namespace InsanityExpressions;

// The ultra-lean result using C# Records
public record HeroDashboard(string Name, string Rank, bool IsLegendary, double PowerLevel);

public class Program
{
    public static void Main()
    {
        // Slice 1: The Data Mapper (From raw DB entity to basic info)
        Expression&amp;lt;Func&amp;lt;string, double, HeroDashboard&amp;gt;&amp;gt; dataMapper = 
            (name, power) =&amp;gt; new HeroDashboard(name, &quot;Unranked&quot;, false, power);

        // Slice 2: The Business Logic (Determines if they are legendary)
        // We want to &quot;inject&quot; this logic into the first expression
        Expression&amp;lt;Func&amp;lt;double, bool&amp;gt;&amp;gt; checkLegendary = p =&amp;gt; p &amp;gt; 9000;

        // THE FUSION: We build a single expression that does both
        var fusedExpression = FuseHeroLogic(dataMapper, checkLegendary);

        Console.WriteLine($&quot;Fused Expression: {fusedExpression}&quot;);

        // Compiling and testing
        var finalFunc = fusedExpression.Compile();
        var result = finalFunc(&quot;Goku&quot;, 9001);

        Console.WriteLine($&quot;Name: {result.Name}&quot;);
        Console.WriteLine($&quot;Is Legendary: {result.IsLegendary}&quot;); // True!
    }

    public static Expression&amp;lt;Func&amp;lt;string, double, HeroDashboard&amp;gt;&amp;gt; FuseHeroLogic(
        Expression&amp;lt;Func&amp;lt;string, double, HeroDashboard&amp;gt;&amp;gt; mapper,
        Expression&amp;lt;Func&amp;lt;double, bool&amp;gt;&amp;gt; logic)
    {
        var nameParam = mapper.Parameters[0];
        var powerParam = mapper.Parameters[1];

        // We &quot;invoke&quot; the logic expression using the power parameter of the mapper
        var logicInvoke = Expression.Invoke(logic, powerParam);

        // We rebuild the Record constructor, but replacing the 'false' with our logic
        var ctor = typeof(HeroDashboard).GetConstructors()[0];
        
        // This is where the magic happens: creating the Record on the fly
        var newRecord = Expression.New(ctor, 
            nameParam, 
            Expression.Constant(&quot;S-Tier&quot;), // Hardcoding a rank change
            logicInvoke,                   // Injected Logic!
            powerParam
        );

        return Expression.Lambda&amp;lt;Func&amp;lt;string, double, HeroDashboard&amp;gt;&amp;gt;(newRecord, nameParam, powerParam);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; The &quot;Vertical Slice&quot; Impact, Imagine your GetHeroById handler. Instead of calling a service that calls a repository, you compose the expressions from those layers into one.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Database: &quot;Oh, I see you need Name, Power, and a calculation of Power &amp;gt; 9000. I'll do that in SQL.&quot;&lt;/li&gt;
&lt;li&gt;Result: You get a HeroDashboard record back. No extra loops, no extra Select statements.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Summary&lt;br&gt;
By the time you reach this level, you aren't just writing code; you are writing code that writes code.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Pro:&lt;/strong&gt; Your app is incredibly fast and memory-efficient. You bypass the &quot;standard developer overhead.&quot;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Con:&lt;/strong&gt; If a Junior developer opens this file, they might think you're performing a ritual to summon a demon.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;My advice? Document this like it's the recipe for eternal life. Because if you lose the context of how these expressions are fused, you'll be debugging &quot;Parameter count mismatch&quot; errors until 2027.&lt;/p&gt;
&lt;p&gt;Furthermore, but no less important, respect: If you're thinking, &quot;This is impractical&quot; or &quot;I'd do it differently,&quot; congratulations: you're already analyzing. But before you dismiss anything, remember that here we build bridges, not walls. If you're looking for a rigid formula, there are a thousand manuals out there; if you're looking to collaborate and expand the boundaries of what's possible, stay. We respect the code, but we respect the process even more. Keep learning wherever you want, but here... here we come to create.&lt;/p&gt;
&lt;p&gt;By One Garlos P. 2026&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/16676/expressions-in-net-from-hello-world-to-matrix-architect</guid>
<pubDate>Mon, 04 May 2026 21:24:58 +0000</pubDate>
</item>
<item>
<title>Everything You Need to Know About Hiring a .NET Development Company</title>
<link>https://coderlegion.com/15561/everything-you-need-to-know-about-hiring-a-net-development-company</link>
<description>&lt;p&gt;The selection of an appropriate .NET development company serves as the foundation for creating digital solutions that deliver dependable performance and scalable capacity and optimal results for contemporary businesses. Businesses need a reliable Software Development Company because they depend on technology for better operational performance and customer service. Businesses use .net development services from professional providers to create secure applications that function efficiently while meeting their needs for market-driven changes. &lt;/p&gt;
&lt;p&gt;A .net development company demonstrates its expertise by delivering advanced technical capabilities in ASP.NET Core framework development and cloud solution implementation and enterprise architecture creation. The built applications satisfy present system needs while enabling future system expansions. The process of selecting the optimal development partner leads to major savings in time and costs while delivering better results for project delivery.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;What is a .NET Development Company?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .net development company specializes in software application development through Microsoft .NET framework design and construction and software application maintenance services. The organizations provide &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.bigscal.com/dotnet-development-services/&quot;&gt;&lt;strong&gt;.net development services&lt;/strong&gt;&lt;/a&gt; which include web application development and enterprise system development and API creation and cloud solution services which are customized for specific business requirements. &lt;/p&gt;
&lt;p&gt;The professional .net development firm creates applications which can grow and protect their system security while delivering exceptional performance throughout the entire development process.The asp net development company creates dynamic web applications through ASP.NET development while the custom .net development company provides businesses with personalized solutions based on their unique needs. &lt;/p&gt;
&lt;p&gt;The top .net development companies deliver dependable results because their teams combine technical abilities with their experience in specific industrial sectors. The best net development companies and Software Development Company partners provide complete development services which include project planning and coding work and software deployment and system upkeep services to help businesses succeed in their digital transformations.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why Businesses Hire a .NET Development Company&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .net development company will deliver secure and scalable applications which enable businesses to achieve their growth targets. Organizations which use .net development services gain access to developers who can create and manage digital systems through their advanced design capabilities. A dependable .net development company delivers projects more quickly while it decreases technical challenges and operational expenses.&lt;/p&gt;
&lt;p&gt;The majority of businesses select either an asp net development company or a custom .net development company to develop specialized applications which match their unique operational needs. The .net development companies possess documented abilities which enable them to handle every project with their advanced tools and industry-standard techniques.&lt;/p&gt;
&lt;p&gt;The selection of an appropriate net development company together with a trustworthy Software Development Company enables organizations to obtain scalable system designs which boost their system efficiency and provide ongoing technical assistance. Businesses utilize .NET specialists to speed up digital changes which improve user experiences and help them stay competitive in the changing technology environment.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key Services Offered by a .NET Development Company&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .net development company offers various services which assist businesses in creating applications that meet security requirements and can expand their operations while maintaining high performance standards. The .net development company provides professional .net development services to create customized web applications and enterprise software systems and cloud-based solutions which meet specific business requirements. &lt;/p&gt;
&lt;p&gt;The asp net development company uses its experience to build applications which use data to boost operational efficiency and enhance user experience. Many organizations use custom .net development companies to create solutions which meet their specific operational needs and industry requirements. &lt;/p&gt;
&lt;p&gt;.Net development companies provide API development services and system integration services and migration services and ongoing maintenance services to ensure clients maintain system stability throughout their operations. The selection of an appropriate net development company or dependable &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.bigscal.com/&quot;&gt;&lt;strong&gt;Software Development Company&lt;/strong&gt;&lt;/a&gt; enables organizations to access contemporary technologies and agile development methods and ongoing assistance.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Factors to Consider When Hiring a .NET Development Company&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The process of choosing a .net development company requires assessment of multiple critical factors which determine whether the project achieves its objectives. The first step requires evaluation of .net development services which includes both web applications and enterprise solutions and cloud integration services. &lt;/p&gt;
&lt;p&gt;A dependable .net development company should possess strong skills to create applications which can scale and maintain security for specific business requirements. The technical skills and industry experience of an asp net development company can be assessed through their previous project work which shows their technical skills and industry knowledge.&lt;/p&gt;
&lt;p&gt;The selection of a custom .net development company should focus on providers who create tailor-made solutions which fulfill your particular needs. Among various .net development companies, prioritize those with transparent communication, agile practices, and proven delivery timelines. The best net development company will also provide long-term maintenance and support. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Benefits of Hiring the Right .NET Development Partner&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The selection of an appropriate .net development company provides businesses with major benefits when they need to create applications that can scale and deliver high performance. The .net development service provider will execute your project through his technical knowhow and contemporary technology and his knowledge of industry standards. &lt;/p&gt;
&lt;p&gt;Your partnership with any .net development company or veteran asp net development company provides you access to developers who create secure and effective solutions which will remain relevant in the future.The custom .net development company creates unique applications which match your business requirements to boost productivity and enhance the user experience. &lt;/p&gt;
&lt;p&gt;The correct partner among elite .net development companies delivers faster product launch times together with lower development risks through their established development methods.The selection of an optimal net development company together with a trusted Software Development Company enables businesses to establish long-lasting system expansion which enables smooth system connectivity and perpetual system maintenance services.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Common Mistakes to Avoid When Hiring&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.bigscal.com/blogs/frontend/innovative-trends-net-development-company/&quot;&gt;&lt;strong&gt;.net development company&lt;/strong&gt;&lt;/a&gt; selection process contains common hiring errors which result in negative effects on project outcomes. The first mistake occurs when organizations select a vendor who provides the lowest price instead of verifying the vendor's skills and their potential for future benefits. The .net development firm should have strong technical skills and proven experience to provide its clients professional .net development solutions. &lt;/p&gt;
&lt;p&gt;The second mistake occurs when organizations fail to consider their needs for scalability and their requirements for upcoming expansions. The asp net development company and custom .net development company should create adaptable solutions which meet the changing requirements of their clients. The clients do not assess portfolios and client testimonials which should be used to select appropriate .net development companies for their projects.&lt;/p&gt;
&lt;p&gt;The project suffers from a severe problem because the team disregards post-launch support which creates a need for maintenance to safeguard system performance and security. The selection of a .net development company or a Software Development Company enables clients to access continuous support services while improving their communication with reduced project risks. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Future Trends in .NET Development&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .NET development field is experiencing quick changes, which forces businesses to hire .net development companies for their technological needs. Current .net development services now adopt cloud-native architectures together with microservices and AI-powered applications to achieve better scalability and performance. &lt;/p&gt;
&lt;p&gt;The .net development company or asp net development company that practices forward-thinking now works to combine .NET technologies with Azure and DevOps pipelines and serverless computing for their customers. The .net development company will develop customized data-based applications which meet particular business requirements in the upcoming years. &lt;/p&gt;
&lt;p&gt;The leading .net development companies use containerization and automation technologies to achieve better deployment processes. The selection of either the top net development company or a trustworthy Software Development Company provides organizations with access to groundbreaking technologies which improve their security measures while enabling their digital development over time. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The selection of a Software Development Company needs to be done correctly because it directly affects the development of dependable applications that can grow and deliver high performance. A trusted .net development firm ensures access to skilled professionals who deliver tailored solutions aligned with business goals. Organizations that use expert .net development services will achieve better operational efficiency, increased performance capabilities, and decreased risks related to their future development processes. Organizations can achieve digital success through their partner evaluation and hiring process because it enables them to maintain secure applications that will stay relevant in future developments while competing with other businesses.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/15561/everything-you-need-to-know-about-hiring-a-net-development-company</guid>
<pubDate>Thu, 23 Apr 2026 03:46:51 +0000</pubDate>
</item>
<item>
<title>How a .NET Development Company Improves Application Security and Performance</title>
<link>https://coderlegion.com/15451/how-a-net-development-company-improves-application-security-and-performance</link>
<description>&lt;p&gt;The .NET development company delivers essential services to create secure high-performance applications which meet contemporary business requirements. Organizations now depend on professional .net development services to create operational applications which can withstand digital security threats and performance challenges because digital ecosystems have become more complex. The .NET development firm uses .NET framework features to build security systems and design optimal system architecture and deliver user-friendly experiences.&lt;/p&gt;
&lt;p&gt;Companies use industry best practices plus advanced tools to protect sensitive data and boost application performance through every stage of their development process. Businesses need to work with experienced .NET development companies because their cybersecurity needs grow while users demand better experiences to help them stay competitive and protect their digital assets and maintain dependable systems which support their business goals.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Understanding the Role of a .NET Development Company&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .NET development company which you hire will develop applications that provide security and scalability and high performance through their work on your specific business requirements. The .NET development companies provide full .NET development services which cover all aspects from initial design to system deployment and ongoing support. &lt;/p&gt;
&lt;p&gt;The .NET development company uses ASP.NET framework together with other frameworks to build secure web applications and desktop software and cloud solutions.The asp net development company which has many years of experience implements secure coding methods while they boost application efficiency and achieve smooth system connections. &lt;/p&gt;
&lt;p&gt;The custom .net development company provides specialized development services which work better than the .NET development company services from top development companies.Organizations work with .net development companies and Software Development Companies to obtain access to developers who use advanced tools and established development practices. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key Security Challenges in Application Development&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .NET development company which you hire will develop applications that provide security and scalability and high performance through their work on your specific business requirements. The .NET development companies provide full .NET development services which cover all aspects from initial design to system deployment and ongoing support. &lt;/p&gt;
&lt;p&gt;The .NET development company uses ASP.NET framework together with other frameworks to build secure web applications and desktop software and cloud solutions.The asp net development company which has many years of experience implements secure coding methods while they boost application efficiency and achieve smooth system connections. &lt;/p&gt;
&lt;p&gt;The custom .net development company provides specialized development services which work better than the .NET development company services from top development companies.Organizations work with .net development companies and Software Development Companies to obtain access to developers who use advanced tools and established development practices. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How a .NET Development Company Enhances Application Security&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .net development company implements industry-standard security measures together with .NET framework security features to protect application security. Businesses receive .net development services which include secure coding standards that protect against SQL injection and cross-site scripting and protection from data breaches. &lt;/p&gt;
&lt;p&gt;The professional .net development firm or asp net development company builds secure authentication and authorization systems which restrict access to sensitive information to validated users. The custom .net development company develops secure applications through its work on data encryption and secure API development and its execution of ongoing security checks. &lt;/p&gt;
&lt;p&gt;The leading .net development companies utilize their advanced threat detection technology together with their security compliance capabilities to safeguard their systems. The best net development company or a trusted Software Development Company delivers continuous system monitoring and software updates while performing ongoing risk assessment activities. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Performance Challenges in Modern Applications&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Modern applications face significant performance challenges because user expectations and data requirements continue to increase. A .net development company needs to solve three main problems which include scalability and latency and resource optimization to create smooth user experiences. &lt;/p&gt;
&lt;p&gt;The .net development services need to implement effective system designs because high traffic volumes will cause system performance issues if they are not properly handled. Poor database queries together with unoptimized code create bottlenecks which decrease system responsiveness to user requests.&lt;/p&gt;
&lt;p&gt;The best asp net development company together with custom .net development companies use caching and load balancing methods and asynchronous programming techniques to improve application performance. Many .net development companies also use cloud integration for their projects because it improves system scalability and system reliability. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How a .NET Development Company Optimizes Performance&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .net development company delivers high-performing applications through its combination of efficient coding practices and modern architecture design. The .net development teams use their expertise to build scalable solutions which employ microservices and caching technologies together with asynchronous programming methods to achieve faster response times and lower latency. &lt;/p&gt;
&lt;p&gt;The .net development company delivers reliable services by optimizing database queries while reducing resource use and creating smooth cloud platform connections.The asp net development company uses its built-in performance functions which include just-in-time compilation and advanced memory management to boost system speed. &lt;/p&gt;
&lt;p&gt;The custom .net development company creates solutions which align with specific business requirements to maintain peak performance during different operational periods. The top .net development companies implement monitoring tools which help them find system bottlenecks while they work to enhance overall operational efficiency.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tools and Technologies Used by .NET Development Companies&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .NET development company requires modern tools and frameworks for building secure and high-performing applications. The top .NET development companies create scalable and efficient solutions through their use of Visual Studio and .NET SDK and ASP.NET Core. A reliable asp net development company also integrates cloud platforms like Microsoft Azure for hosting, monitoring, and auto-scaling applications. &lt;/p&gt;
&lt;p&gt;Organizations use SQL Server and Entity Framework as their primary database management tools to achieve optimal data access and safeguard data security.The custom .NET development company uses DevOps tools such as Docker and Kubernetes and Azure DevOps for continuous integration and deployment to improve both performance and security.&lt;/p&gt;
&lt;p&gt;Developers need testing frameworks which include NUnit and xUnit because those tools help them to maintain code quality standards. Security tools which include built-in .NET authentication libraries provide protection for applications against potential security vulnerabilities.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Benefits of Hiring a Professional .NET Development Company&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Businesses building secure high-performing applications receive major benefits from hiring professional .NET development companies. A skilled .net development company ensures that applications are developed using industry best practices, which leads to security improvements and reduces the chances of security breaches. &lt;/p&gt;
&lt;p&gt;A reliable .net development firm uses its advanced frameworks and tools to create secure coding standards and encryption methods and authentication systems that protect sensitive data from threats.The top asp net development company works to improve application performance through its development of efficient architecture and caching strategies and scalable cloud solutions. &lt;/p&gt;
&lt;p&gt;The custom .net development company delivers specialized solutions which meet the specific operational requirements of businesses that select this service. Leading .net development companies provide ongoing maintenance services together with performance monitoring services to maintain stability throughout extended periods.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A trustworthy .net development company creates secure applications which perform optimally to meet current business requirements. The .net development company uses advanced tools and best practices together with continuous monitoring to provide effective security solutions which maintain system performance and scalability. Professional .net development services create better application performance which helps businesses achieve their digital goals through improved user experiences.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/15451/how-a-net-development-company-improves-application-security-and-performance</guid>
<pubDate>Wed, 22 Apr 2026 04:31:07 +0000</pubDate>
</item>
<item>
<title>How a .NET Development Company Powers Modern Business Applications</title>
<link>https://coderlegion.com/15450/how-a-net-development-company-powers-modern-business-applications</link>
<description>&lt;p&gt;The current software development company assists businesses by creating digital products that can scale and remain secure while delivering high performance. The .NET framework has become the top choice for enterprise application development because it provides developers with development options that they can rely on to create applications which run across different platforms. &lt;/p&gt;
&lt;p&gt;A professional .net development company leverages these strengths to design and deliver powerful business applications that meet evolving market demands. Organizations use .net development services to create web and mobile and cloud solutions which match their unique operational requirements. Businesses use these services to create better workflows which result in higher efficiency and better customer experiences. &lt;/p&gt;
&lt;p&gt;A trusted .net development firm focuses on combining modern architecture, secure coding practices, and advanced development tools to ensure robust application performance. .NET enables businesses to achieve their digital transformation goals because it provides them with innovative solutions which can scale up their operations and link their systems together. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Understanding a .NET Development Company&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A .net development company is a specialized technology partner that designs, builds, and maintains scalable business applications using Microsoft’s .NET framework. The companies provide complete .net development services which include development of web applications and enterprise software and cloud-based systems and application programming interface integrations that businesses require. &lt;/p&gt;
&lt;p&gt;The professional .net development firm creates digital solutions which are secure and high-performing and future-ready to help businesses grow and operate more efficiently.The experienced asp net development company creates strong backend systems together with interactive web applications, while the custom .net development company delivers specific solutions for different industry needs. &lt;/p&gt;
&lt;p&gt;.Net development companies apply modern technologies to their work which includes cloud computing and microservices and DevOps to boost their operational capacity and business growth.The best net development company together with a trusted Software Development Company provides access to skilled developers who deliver optimal architectural solutions and dependable client assistance. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Role of .NET in Modern Application Development&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;.NET plays a vital role in contemporary application development because it enables developers to create business solutions that can grow in size while maintaining security and optimal system performance. The top .net development company uses the framework to build applications that handle complex business needs. Businesses can create web, desktop, and cloud-based solutions through advanced .net development services which deliver uninterrupted performance on all platforms.&lt;/p&gt;
&lt;p&gt;The .NET framework enables trusted asp net development companies and custom .net development companies to build flexible applications which help their clients achieve their business objectives. .NET development companies use the framework's adaptable features to build systems which combine cloud computing and API and microservices technologies for better resource management and scaling capabilities.&lt;/p&gt;
&lt;p&gt;The best net development company or experienced .net development firm uses .NET tools and libraries to achieve faster development times while enhancing security measures and improving system performance. The .NET framework enables professional software development companies to create applications which businesses can depend on for future digital requirements while maintaining system reliability and easy maintenance.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How a .NET Development Company Powers Applications&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .net development company provides crucial support to modern businesses by developing digital solutions which enable businesses to create applications that can grow secure and perform at high levels. Companies achieve operational efficiency through advanced .net development services which enable them to create web applications mobile applications and cloud-based solutions. &lt;/p&gt;
&lt;p&gt;An asp net development company specializes in building strong system designs which enable organizations to meet their complex business demands while creating smooth customer experiences.The custom .net development company creates customized software solutions which help businesses achieve their particular objectives while maintaining flexibility and seamless third-party system connections. &lt;/p&gt;
&lt;p&gt;The leading .net development companies use automation along with API development and cloud technologies to improve their applications' operational capabilities.The top net development company or experienced .net development firm ensures optimized performance, strong security measures, and continuous support throughout the development lifecycle. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Security Features in .NET Applications&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .NET framework provides modern applications with strong security features which make it the best choice for enterprise businesses. The .net development company uses advanced security systems to safeguard their applications against data breaches and cyberattacks. The .net development services enable businesses to access pre-installed authentication and authorization and secure session management frameworks.&lt;/p&gt;
&lt;p&gt;The asp net development company and custom .net development company provide protection for sensitive information by implementing encryption measures which comply with established industry standards. The top .net development organizations use secure coding techniques together with ongoing vulnerability testing to achieve application security. &lt;/p&gt;
&lt;p&gt;The best net development company or experienced .net development firm integrates multi-factor authentication, role-based access control, and compliance standards to enhance protection. The software development company which uses .NET technology develops business applications which provide security and scalability and resilience while protecting sensitive information and delivering an uninterrupted user experience.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Performance Optimization Strategies&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .net development company focuses on performance optimization to create business applications which deliver high-speed performance and scalability and dependable operation. Advanced .net development services enable developers to establish efficient coding methods which decrease memory usage and boost application performance. &lt;/p&gt;
&lt;p&gt;Professional asp net development companies achieve continuous operation during peak usage periods through their use of asynchronous programming and caching systems and their implementation of database query optimization techniques. The trusted custom .net development company uses microservices and load balancing to improve workload distribution based on their architectural design work. &lt;/p&gt;
&lt;p&gt;The leading .net development companies use performance monitoring tools to find performance issues which they use to enhance application performance through ongoing application tuning. The best net development company or experienced .net development firm ensures applications remain scalable and responsive as business needs grow. Software Development Companies which establish trust deliver deployment acceleration and system performance gains through their implementation of DevOps and cloud optimization methods.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Technologies Used by .NET Development Companies&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The current technology stack of a .net development company enables the creation of secure and scalable applications which the company delivers through its advanced technology capabilities. The top .net development service providers use ASP.NET Core and MVC and .NET 8 frameworks to create high-performance web applications and enterprise solutions. &lt;/p&gt;
&lt;p&gt;A trustworthy asp net development company implements cloud solutions through Microsoft Azure and AWS to deliver flexible infrastructure and scaling capacity and smooth operational transitions.The custom .net development company utilizes DevOps tools which include Azure DevOps and Jenkins and Docker to establish continuous integration and delivery processes that enhance their development productivity. &lt;/p&gt;
&lt;p&gt;The modern databases which .net development companies use for their data management needs include SQL Server and PostgreSQL. The leading net development company or the skilled .net development firm uses API development and microservices architecture and front-end frameworks like Angular or React to deliver complete full-stack solutions.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Benefits of Hiring a .NET Development Company&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Businesses gain flexible and protected digital solutions through .NET development company services which deliver both scalable and high-performance solutions for current business requirements. A professional .net development company delivers robust applications that improve efficiency and streamline operations through advanced architecture and clean coding practices.&lt;/p&gt;
&lt;p&gt;Businesses achieve faster development cycles and reduced downtime and improved system reliability through expert .net development service usage.Trusted asp net development companies and custom .net development firms design solutions which help businesses achieve their specific objectives while providing them with adaptable systems which grow with their needs. &lt;/p&gt;
&lt;p&gt;Leading .net development companies also provide strong security measures which protect applications from potential cyber threats while they comply with required security regulations.Organizations can establish connections with advanced .net development companies or experienced .net development firms which enable them to use contemporary technologies including cloud integration and APIs and automation tools.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Future of .NET in Business Applications&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .NET platform will drive business application development through ongoing technological advancements which businesses adopt through their cloud systems and through their use of intelligent automation technologies. A modern .net development company uses emerging AI and machine learning and microservices technologies to create enterprise solutions which can grow with business needs. &lt;/p&gt;
&lt;p&gt;Modern .net development services enable organizations to develop secure, high-performance applications that adapt quickly to changing market demands. The custom .net development company together with the asp net development company delivers businesses flexible solutions which enhance their operational agility and productivity. &lt;/p&gt;
&lt;p&gt;.NET development companies increasingly adopt DevOps together with cloud-native architectures because digital transformation accelerates their ability to deliver software at greater speed with improved system reliability. .net development firms or the best net development company deliver extended project value through their commitment to establishing security systems and automation processes and performance enhancement methods. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .NET development company develops business applications which enable digital transformation through secure and scalable systems and high-performance applications. Advanced .net development services help businesses to operate more efficiently by enhancing their operational processes and creating better user experiences. The dependable .net development company provides two essential services which include building strong system designs and enabling smooth system connections while maintaining application performance for an extended period. Organizations that work with experienced Software Development Companies can maintain their market competitiveness while protecting their business applications through continuous security updates and performance enhancements.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/15450/how-a-net-development-company-powers-modern-business-applications</guid>
<pubDate>Wed, 22 Apr 2026 03:55:02 +0000</pubDate>
</item>
<item>
<title>Why Businesses Choose a .NET Development Company for Scalable Solutions</title>
<link>https://coderlegion.com/15039/why-businesses-choose-a-net-development-company-for-scalable-solutions</link>
<description>&lt;p&gt;Businesses need strong and expandable applications to maintain their market position and handle increased user traffic in the rapidly changing digital world. The professional .net development company provides essential support to fulfill this requirement. Organizations can leverage .NET framework functions for their development of high-performance and secure solutions which meet their specific requirements. Enterprises depend on expert .net development services to achieve smooth application development and system integration while maintaining operational capacity across different platforms.&lt;/p&gt;
&lt;p&gt;The .net development firm provides trusted technical skills and extensive industry knowledge together with strategic business guidance that helps organizations speed up their development processes without compromising product quality. .NET provides all necessary resources to businesses for growing their operations across enterprise software and cloud applications and contemporary web development platforms. The correct development experts should be chosen by businesses who want to succeed in their digital transformation and growth initiatives.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Understanding the .NET Framework&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Microsoft developed the .NET framework as a powerful platform which allows developers to create applications that can scale secure systems while delivering high-performance results. The platform enables developers to create applications for web desktop mobile and cloud environments by supporting multiple programming languages which include C# programming language. Companies use .net development services from either .net development companies or custom .net development companies to use this framework properly.&lt;/p&gt;
&lt;p&gt;The &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.bigscal.com/dotnet-development-services/&quot;&gt;&lt;strong&gt;.net development services&lt;/strong&gt;&lt;/a&gt; which professional .net development firms and asp net development companies provide enable businesses to create applications which integrate seamlessly with their existing systems while delivering flexible solutions and faster deployment times. The top net development company and experienced .net development companies help organizations create enterprise-grade solutions based on their expertise. The Software Development Company uses .NET to create reliable applications which can expand their capacity while securing performance and protection standards for multiple industries.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Importance of Scalability in Modern Applications&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The development of contemporary applications requires organizations to use scalability as an essential element which enables them to manage increasing user demands, data expansion, and changing market conditions without performance degradation. A reliable .net development company establishes efficient system scaling methods which enable their clients to achieve permanent system stability at reduced operational costs. &lt;/p&gt;
&lt;p&gt;Business operations use .net development services to build flexible systems which enable vertical and horizontal growth.An established asp net development company together with a custom .net development company creates applications which handle higher workload demands to help businesses keep their competitive advantage. Most .net development companies concentrate on developing cloud integration solutions together with microservices to improve their systems' ability to scale. &lt;/p&gt;
&lt;p&gt;The selection of either the top net development company or a reliable Software Development Company provides businesses with access to cutting-edge technical resources and specialized knowledge. The implementation of .net development services enables businesses to protect their applications from future changes while they maintain continuous delivery of superior user experiences.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why Choose a .NET Development Company&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The selection of a .NET development company enables businesses to receive dependable and expandable and high-performance applications which meet their specific requirements. A professional team offering .net development services brings deep expertise in building secure and flexible solutions using modern technologies. &lt;/p&gt;
&lt;p&gt;When you engage with a .net development firm or an asp net development company, you gain access to developers who possess expertise in handling enterprise-level project demands.The custom .net development company develops specific applications which match your business objectives while providing smooth integration and future growth possibilities. The majority of .net development companies offer ongoing support services, which help organizations minimize their operational risks across extended time periods. &lt;/p&gt;
&lt;p&gt;The top net development company enables businesses to boost their market entry speed without compromising their product quality or performance benchmarks.Business organizations pursuing sustainable development need to select &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.bigscal.com/&quot;&gt;&lt;strong&gt;Software Development Company&lt;/strong&gt;&lt;/a&gt; as their partner because its .NET ecosystem helps them build cloud-ready solutions which maintain cost-effective operations.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key Features of .NET for Scalable Solutions&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;.NET provides developers with a high-performance building platform which enables them to create applications that can seamlessly expand their capabilities and their operational efficiency. The Software Development Company can develop applications which operate smoothly on Windows and Linux and macOS because of their cross-platform system capabilities. &lt;/p&gt;
&lt;p&gt;The built-in cloud integration capabilities Microsoft Azure provides businesses with a simple way to expand their resource capacity according to their current needs.The security framework of .net development services provides strong protection which safeguards data while helping organizations meet their compliance requirements. &lt;/p&gt;
&lt;p&gt;The combination of microservices architecture with containerization technology enables a custom .net development company to build systems that can adjust their capacity to meet changing needs. The continuous updates of the system provide high performance which makes it the preferred option for both asp net development companies and .net development firms. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Benefits of Hiring a Professional .NET Development Company&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;.NET development companies provide businesses with essential support for developing secure and expandable applications through their professional development services. The .net development company provides dependable services through its technical expertise which enables delivery of custom solutions that meet client requirements. &lt;/p&gt;
&lt;p&gt;Organizations that use .net development services can achieve faster development cycles without sacrificing their system performance or operational agility. Developers who use contemporary methods and tools work together with .net development partners and asp net development companies to deliver their expertise to clients. &lt;/p&gt;
&lt;p&gt;The custom .net development company creates solutions which match the specific operational requirements of its clients to enhance their operational efficiency and user satisfaction. The leading .net development companies deliver continuous system maintenance together with system updates and system compatibility support for existing customer systems. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Use Cases of .NET in Scalable Business Applications&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;companies from all sectors use .NET framework. to develop systems which provide better performance while supporting future user growth. A professional .net development company helps organizations design enterprise-grade systems such as customer relationship management (CRM) platforms, enterprise resource planning (ERP) systems, and large-scale eCommerce applications.&lt;/p&gt;
&lt;p&gt;A custom .net development company provides organizations with unique solutions which function according to their specific requirements while maintaining both performance and security standards.Many .net development companies also specialize in building cloud-based SaaS platforms that require seamless scalability and uptime. The asp net development company creates web applications that maintain fast performance during periods of high user traffic. &lt;/p&gt;
&lt;p&gt;The top net development company or trusted .net development firm helps businesses integrate their systems with AI technologies, IoT devices, and data analytics solutions.The Software Development Company uses dot net development services to enable businesses to connect their systems with existing software while they expand their systems and maintain their operations.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Comparison with Other Development Technologies&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The assessment of development stacks by businesses begins with a comparison between .NET and other programming languages which include Java, Node.js, and Python-based frameworks. A .NET Development Company stands out from its competitors because its enterprise support and security features and ability to handle large-scale applications function as its primary strengths.&lt;/p&gt;
&lt;p&gt;.NET enables users to work with Microsoft tools more effectively, while Java development takes longer to complete. The system delivers better organizational support for enterprise-grade applications, which need complete system performance and Node.js compatibility. &lt;/p&gt;
&lt;p&gt;Python frameworks specialize in artificial intelligence and data science work, while .NET provides better capabilities for creating dependable business software that operates in production environments.The &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.bigscal.com/blogs/frontend/innovative-trends-net-development-company/&quot;&gt;&lt;strong&gt;.NET development company&lt;/strong&gt;&lt;/a&gt; or .NET development firm delivers complete .NET development services for their clients which results in easier deployment and ongoing maintenance work.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How to Choose the Right .NET Development Company&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The process of selecting an appropriate partner remains vital for the development of applications which need to grow and maintain their security. The .net development company must demonstrate its ability to deliver enterprise-level solutions through modern Microsoft technologies which it has already established as reliable expertise. The assessment should begin with an examination of their technical abilities which need to include ASP.NET and cloud integration and microservices architecture. &lt;/p&gt;
&lt;p&gt;A reliable asp net development company needs to show its capability to create and manage applications which function at high traffic levels and require intricate systems to operate. The web sites of various .net development firms need evaluation to find out their experience in different fields and their previous successful projects. A reliable custom .net development company should provide customized services for each client rather than using standard solutions which apply to all customers. &lt;/p&gt;
&lt;p&gt;The company needs to deliver complete .net development services which encompass the entire process from design to development and deployment and maintenance. The company needs to present their work through client testimonials and case studies while also showing their ability to handle communication with clients. The top net development company will deliver solutions which prioritize both security and scalability while providing ongoing support for extended periods. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Future of .NET in Scalable Application Development&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The future of .NET will provide highly promising prospects for developing scalable applications because businesses require cloud-ready solutions with flexible operation and high-performance capabilities. A modern .NET development company helps organizations build enterprise-grade applications which enable their business growth through its essential development services. &lt;br&gt;
The ongoing advancement of cloud computing and microservices technology and AI integration has created new .NET development services which allow businesses to build secure and efficient systems. All leading .NET development companies and every forward-thinking .NET development firm are adopting .NET 8+ to deliver cross-platform and containerized solutions. &lt;br&gt;
The ASP.NET development company and custom .NET development company both provide businesses with custom solutions which fulfill their specific requirements. The best .NET development company stands out in the market because it provides innovative solutions which help them achieve business growth and operational flexibility and dependability. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The selection of a .NET development company enables organizations to create applications which can expand while maintaining safety and delivering optimal performance for their growth requirements. The .net development services provide organizations with contemporary technological solutions and cloud-based software and dependable operational assistance. The dedicated .net development company delivers both budget control and efficient project implementation while providing enduring advantages to clients. Experienced professionals enable companies to maintain market competitiveness while their digital needs evolve through the development of innovative solutions which can be scaled to handle upcoming business demands while ensuring security and operational effectiveness across different commercial environments.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/15039/why-businesses-choose-a-net-development-company-for-scalable-solutions</guid>
<pubDate>Fri, 17 Apr 2026 07:53:49 +0000</pubDate>
</item>
<item>
<title>How .NET Development Companies Modernize Legacy Systems</title>
<link>https://coderlegion.com/14933/how-net-development-companies-modernize-legacy-systems</link>
<description>&lt;p&gt;The outdated systems which many businesses use today create substantial difficulties because they prevent organizations from expanding their operations and achieving better performance results and developing new technologies. A modern .NET development company plays a vital role in transforming these outdated systems into efficient, cloud-ready solutions. The .NET development firm uses its advanced frameworks and tools to assist businesses with application migration and refactoring and optimization tasks while maintaining their essential business operations. Organizations need this transformation to achieve competitive advantage in their digital environment which keeps changing rapidly.&lt;/p&gt;
&lt;p&gt;Through specialized .NET development services, companies can modernize legacy applications by adopting microservices architecture, integrating APIs, and moving workloads to cloud platforms like Microsoft Azure. The services maintain both enterprise system security and operational performance capabilities through dedicated systems which deliver ongoing protection and operational support. A skilled .NET development company not only upgrades technology but also aligns IT infrastructure with current business goals. Modernization provides enterprises with flexible operations and lower operational expenses and improved customer experiences which makes it a required business strategy.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Role of a .NET Development Company in Legacy Modernization&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .NET development company provides vital services which help organizations upgrade their outdated systems into contemporary scalable systems that operate with enhanced efficiency. Through expert &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.bigscal.com/dotnet-development-services/&quot;&gt;&lt;strong&gt;.net development services&lt;/strong&gt;&lt;/a&gt; organizations assess their legacy systems to find performance issues and create a complete plan for system modernization. &lt;/p&gt;
&lt;p&gt;The custom .NET development company provides trusted services which enable organizations to modernize their aging monolithic systems through cloud-native and microservices re-architecting methods.The ASP.NET development company provides services which help clients move their existing web applications to the ASP.NET Core framework. &lt;/p&gt;
&lt;p&gt;The .NET development companies and the trusted .NET development firm develop systems that use APIs for automation and data migration which allows business operations to continue without interruptions.The best net development company partnership enables enterprises to decrease their technical debt while achieving better system performance and cost savings that last for years. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Challenges of Legacy System Modernization&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Every .NET development company needs to handle the difficult task of modernizing legacy systems according to their established operational procedures. The first main obstacle of the project involves managing outdated systems which require advanced .NET development services to achieve successful modernization. Organizations depend on custom .NET development companies or ASP.NET development companies to solve their compatibility challenges while their operations continue without interruption.&lt;/p&gt;
&lt;p&gt;The second major obstacle businesses face during data migration occurs when they need to protect sensitive data through secure transfer methods that prevent any data loss or corruption. A .NET development firm needs to fix both performance bottlenecks and security vulnerabilities which exist in legacy systems according to the requirements of their work for top .NET development companies.&lt;/p&gt;
&lt;p&gt;The process of modernization becomes more difficult because documentation is insufficient and outdated technologies create a need for extended time periods. The selection between an excellent development company and a reliable Software Development Company establishes which development company will provide maximum risk reduction. Successful legacy system transformation requires both detailed planning and professional execution according to the established requirements.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Approaches Used by .NET Development Companies&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A modern .NET development company plays a vital role in transforming outdated systems through structured modernization strategies. Replatforming constitutes one of the primary methods which custom .NET development companies use to move legacy applications into modern frameworks through .NET Core and .NET 8 migrations while maintaining their original functions.&lt;/p&gt;
&lt;p&gt;The best net development company uses refactoring to improve existing code which results in better performance and scalability and security enhancements.Many .NET development companies also use rearchitecting techniques which transform monolithic systems into microservices through .net development services to achieve better system flexibility. The process of API integration creates a crucial method which establishes direct communication links between outdated systems and contemporary systems. &lt;/p&gt;
&lt;p&gt;The experienced ASP.NET development company improves its scalability through Microsoft Azure cloud platforms which also helps the company decrease its expenses for infrastructure.A leading .NET development firm or &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.bigscal.com/&quot;&gt;&lt;strong&gt;Software Development Company&lt;/strong&gt;&lt;/a&gt; uses automation together with DevOps and CI/CD pipelines to achieve continuous modernization processes which create minimal disruptions for their business operations.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tools and Technologies in .NET Modernization&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The .NET development company utilizes its advanced technology stack to execute system modernization through advanced tools and expert knowledge. The .net development companies use ASP.NET Core and .NET 8+ and C# to transform existing applications into better performing systems which can handle increased user demand. &lt;/p&gt;
&lt;p&gt;Microsoft Azure public cloud platform provides essential services which support organizations to migrate systems and create container-based applications and execute hybrid deployment methods.The custom .NET development company uses DevOps tools which include Azure DevOps and Jenkins and GitHub Actions to create CI/CD pipelines which enable rapid and secure software delivery. &lt;/p&gt;
&lt;p&gt;The best net development company uses microservices architecture and Docker containers to create modular system components which replace traditional monolithic software design.The trusted Software Development Company uses API management tools and security frameworks and monitoring solutions to maintain system stability in the .NET development services they provide. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Benefits of Modernizing with a .NET Development Company&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Businesses that want to maintain digital competitiveness should use .NET development services to modernize their existing systems. The trusted custom .NET development company delivers advanced .NET development services to help organizations transform their outdated infrastructure into secure and high-performing scalable solutions. &lt;/p&gt;
&lt;p&gt;The performance of a business system will be enhanced while downtime will be reduced through work with experienced .NET development companies.The ASP.NET development company provides customers with seamless framework migration services that help them move to ASP.NET Core which improves their ability to connect with cloud services and work across different platforms. &lt;/p&gt;
&lt;p&gt;The top .NET development firm helps businesses decrease their operational expenses by eliminating technical debt and making their systems easier to manage. The best net development company uses automation and DevOps and microservices architecture to drive innovation at an accelerated pace. The Software Development Company specializing in .NET supports enterprises through effective legacy system modernization.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Choosing the Right .NET Development Company&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The process of selecting a .NET development company requires businesses to choose the most appropriate company to achieve their goal of updating outdated systems. The evaluation process for custom .NET development company selection should begin with an assessment of their expertise and technical skills and their experience in specific industries. &lt;/p&gt;
&lt;p&gt;The top .NET development company will showcase its legacy modernization work through multiple successful projects which demonstrate its expertise with Microsoft technologies including .NET Core and Azure. A Software Development Company must be selected according to its ability to adopt contemporary development methods which include DevOps and microservices architecture and agile development practice.&lt;/p&gt;
&lt;p&gt;A trusted partner delivers transformation results through which organizations achieve better performance outcomes and enhanced security features and greater system capacity. The .NET development company which best fits the business needs of the organization enables companies to perform system upgrades through digital solutions which achieve both modern requirements and future business expansion goals.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Future of Legacy System Modernization&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The advanced development services of .NET development services allow organizations to modernize their outdated legacy systems through cloud-enabled agile infrastructure solutions. A modern .NET development company plays a crucial role in helping businesses migrate from monolithic architectures to scalable microservices and API-driven ecosystems. &lt;/p&gt;
&lt;p&gt;The custom &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.bigscal.com/blogs/frontend/innovative-trends-net-development-company/&quot;&gt;&lt;strong&gt;.NET development company&lt;/strong&gt;&lt;/a&gt; provides businesses with tailored modernization strategies which meet their specific business goals as their demand for services increases. All .NET development firms and .NET development companies are now using AI and automation together with cloud-first solutions to modernize their existing systems because Microsoft technologies keep developing at a fast pace. &lt;/p&gt;
&lt;p&gt;The professional ASP.NET development company enables enterprises to enhance their system performance while maintaining better security and operational capacity through its development services. The leading Software Development Company and the best net development company specialize in three main areas which include application reengineering and modern DevOps practice integration together with seamless migration. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The digital environment of contemporary business demands that organizations update their outdated systems to maintain their market position. The .NET development company provides trustworthy services which help organizations update their old systems to create secure and advanced scalable performance systems. Advanced .NET development services enable businesses to upgrade their systems through smooth transitions to modern cloud and microservices architectures. The .NET development firm uses its expert knowledge to move projects forward while decreasing potential problems and increasing operational efficiency. The partnership with a skilled provider creates a path for continuous business growth and enhances system performance and fosters ongoing innovation throughout enterprise applications.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/14933/how-net-development-companies-modernize-legacy-systems</guid>
<pubDate>Thu, 16 Apr 2026 04:08:15 +0000</pubDate>
</item>
<item>
<title># The Rule Pattern in C#, and Why It Works So Well with the Result Pattern</title>
<link>https://coderlegion.com/14143/the-rule-pattern-in-c-and-why-it-works-so-well-with-the-result-pattern</link>
<description>&lt;h2 id=&quot;the-rule-pattern-in-c-and-why-it-works-so-well-with-the-result-pattern&quot;&gt;The Rule Pattern in C#, and Why It Works So Well with the Result Pattern&lt;/h2&gt;
&lt;p&gt;Business rules rarely stay in one place.&lt;/p&gt;
&lt;p&gt;A small validation starts in a command handler. Another check appears in a service. A third gets added somewhere in the domain. A few weeks later, the real business policy is scattered across the application, and nobody can see it clearly anymore.&lt;/p&gt;
&lt;p&gt;That is exactly where the Rule pattern becomes useful.&lt;/p&gt;
&lt;p&gt;At its core, the idea is simple. Instead of expressing business decisions as anonymous conditionals spread throughout the system, you give each rule a name and wrap it in its own object. Martin Fowler describes this style through the Specification pattern, where the statement of what satisfies a candidate is separated from the candidate itself, and those specifications can be combined into richer logic. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://martinfowler.com/apsupp/spec.pdf?utm_source=chatgpt.com&quot; title=&quot;Specifications&quot;&gt;martinfowler.com&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;In practical C# applications, especially the ones using CQRS or domain-driven design, that gives you something powerful: business rules that are explicit, reusable, and easy to reason about. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://martinfowler.com/apsupp/spec.pdf?utm_source=chatgpt.com&quot; title=&quot;Specifications&quot;&gt;martinfowler.com&lt;/a&gt;)&lt;/p&gt;
&lt;h3 id=&quot;what-the-rule-pattern-really-solves&quot;&gt;What the Rule pattern really solves&lt;/h3&gt;
&lt;p&gt;The biggest problem is not that business checks exist. The problem is that they often exist in the wrong shape.&lt;/p&gt;
&lt;p&gt;When rules are buried inside handlers, services, or controller actions, they are hard to spot, hard to test in isolation, and very easy to duplicate. The code still works, but the business language disappears.&lt;/p&gt;
&lt;p&gt;The Rule pattern fixes that by turning each business condition into a named concept. Instead of asking developers to interpret a chain of low-level checks, the code starts speaking in terms the business would actually recognize. That is very much in line with DDD’s emphasis on modeling around the real language of the domain. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/ddd-oriented-microservice?utm_source=chatgpt.com&quot; title=&quot;Designing a DDD-oriented microservice - .NET&quot;&gt;Microsoft Learn&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;In other words, the pattern is not just about validation. It is about clarity.&lt;/p&gt;
&lt;h3 id=&quot;why-it-is-often-called-the-specification-pattern&quot;&gt;Why it is often called the Specification pattern&lt;/h3&gt;
&lt;p&gt;If the shape feels familiar, that is because it usually is. What many teams call a Rule pattern is very close to what Fowler documented as Specification. The core idea is to represent business criteria as composable objects rather than raw conditionals, and then combine them with logical operations like AND, OR, and NOT. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://martinfowler.com/apsupp/spec.pdf?utm_source=chatgpt.com&quot; title=&quot;Specifications&quot;&gt;martinfowler.com&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;That is why this pattern tends to feel so natural in real systems. Business rules are rarely isolated. More often, they are layered:&lt;/p&gt;
&lt;p&gt;A customer must be verified.&lt;br&gt;
An order must reach a minimum amount.&lt;br&gt;
A credit limit must not be exceeded.&lt;/p&gt;
&lt;p&gt;On their own, each rule is simple. The real value appears when they can be combined into a meaningful policy.&lt;/p&gt;
&lt;h3 id=&quot;why-this-pattern-becomes-more-valuable-as-the-system-grows&quot;&gt;Why this pattern becomes more valuable as the system grows&lt;/h3&gt;
&lt;p&gt;At first, a few inline checks seem harmless. But as the application grows, the cost of hidden business logic grows with it.&lt;/p&gt;
&lt;p&gt;Rules get copied into multiple workflows.&lt;br&gt;
One endpoint enforces them, another forgets.&lt;br&gt;
A handler applies three checks, a background job applies only two.&lt;br&gt;
Tests start focusing on branches instead of policies.&lt;/p&gt;
&lt;p&gt;When rules become standalone concepts, those problems start to shrink. You can test a rule directly. You can reuse it in multiple flows. You can combine it with other rules. Most importantly, you can read the application flow and understand what it is trying to protect.&lt;/p&gt;
&lt;p&gt;That is one of the reasons this pattern fits so well in systems that care about maintainability.&lt;/p&gt;
&lt;h3 id=&quot;where-the-result-pattern-fits&quot;&gt;Where the Result pattern fits&lt;/h3&gt;
&lt;p&gt;The Rule pattern answers one question:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Is this action allowed according to the business?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The Result pattern answers another:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;What happened when we tried to perform it?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;That separation is the reason the two patterns fit together so well.&lt;/p&gt;
&lt;p&gt;The rule evaluates business truth.&lt;br&gt;
The result communicates application outcome.&lt;/p&gt;
&lt;p&gt;Vladimir Khorikov’s writing on Result-based error handling makes this distinction especially useful for expected failures. Instead of throwing exceptions for normal business rejections, you can return an explicit failure outcome and keep the flow predictable. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://enterprisecraftsmanship.com/posts/error-handling-exception-or-result/?utm_source=chatgpt.com&quot; title=&quot;Error handling: Exception or Result?&quot;&gt;Enterprise Craftsmanship&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;That gives you a very clean mental model:&lt;/p&gt;
&lt;p&gt;The domain decides.&lt;br&gt;
The application reports.&lt;/p&gt;
&lt;h3 id=&quot;why-this-pairing-feels-so-clean-in-practice&quot;&gt;Why this pairing feels so clean in practice&lt;/h3&gt;
&lt;p&gt;A good rule object should not care about HTTP, API responses, logging, UI wording, or transport concerns. Its responsibility is much smaller. It answers whether a business condition holds.&lt;/p&gt;
&lt;p&gt;The application layer then takes that answer and decides what to do next. If the rule fails, the application can return a failure result. If it passes, the use case continues.&lt;/p&gt;
&lt;p&gt;This separation lines up well with Microsoft’s DDD guidance, which treats validations as invariants and emphasizes that aggregates are responsible for enforcing consistency across state changes. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-model-layer-validations?utm_source=chatgpt.com&quot; title=&quot;Designing validations in the domain model layer - .NET&quot;&gt;Microsoft Learn&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;That is why the combination works so well. The rule keeps business logic clean. The result keeps flow control clean.&lt;/p&gt;
&lt;h3 id=&quot;a-simple-order-example-without-the-code&quot;&gt;A simple order example, without the code&lt;/h3&gt;
&lt;p&gt;Imagine an order placement use case with three policies:&lt;/p&gt;
&lt;p&gt;The order must meet a minimum amount.&lt;br&gt;
The customer must be verified.&lt;br&gt;
The order must stay within the customer’s credit limit.&lt;/p&gt;
&lt;p&gt;Without a rule-based approach, those checks often end up inline inside the command handler. That works, but the handler slowly becomes the place where business policy lives.&lt;/p&gt;
&lt;p&gt;With a rule-based approach, those policies become named rules. The handler simply coordinates the workflow: load data, build the order, evaluate the rule set, return a success or failure result, and persist when everything is valid.&lt;/p&gt;
&lt;p&gt;That is a much healthier separation of concerns.&lt;/p&gt;
&lt;p&gt;The handler stops being the place where business logic is invented, and becomes the place where business logic is orchestrated.&lt;/p&gt;
&lt;h3 id=&quot;the-biggest-benefit-is-not-flexibility-it-is-readability&quot;&gt;The biggest benefit is not flexibility, it is readability&lt;/h3&gt;
&lt;p&gt;People often talk about this pattern in terms of reuse or composability, and those are real benefits.&lt;/p&gt;
&lt;p&gt;But the biggest benefit is readability.&lt;/p&gt;
&lt;p&gt;When rules are named well, the code starts reading like a business conversation instead of a technical negotiation. That matters more than people think. Clear code reduces mistakes, speeds up maintenance, and makes onboarding easier for everyone who touches the system later.&lt;/p&gt;
&lt;p&gt;A long chain of conditionals tells you how the system behaves.&lt;/p&gt;
&lt;p&gt;A well-named rule tells you why.&lt;/p&gt;
&lt;h3 id=&quot;one-important-design-note&quot;&gt;One important design note&lt;/h3&gt;
&lt;p&gt;There is one trap worth mentioning.&lt;/p&gt;
&lt;p&gt;Just because a rule is expressed cleanly does not automatically mean it belongs in the application layer.&lt;/p&gt;
&lt;p&gt;Some rules are just use-case checks. Those can live comfortably near the workflow.&lt;/p&gt;
&lt;p&gt;But some rules are true invariants of the domain. Those should usually be protected by the aggregate itself. Microsoft’s guidance is very clear on this point: aggregates are responsible for enforcing invariants across state changes. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-model-layer-validations?utm_source=chatgpt.com&quot; title=&quot;Designing validations in the domain model layer - .NET&quot;&gt;Microsoft Learn&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;So the right question is not only, “Can I model this as a rule?”&lt;/p&gt;
&lt;p&gt;The better question is, “Who is responsible for protecting this rule?”&lt;/p&gt;
&lt;p&gt;If the answer is “the domain itself,” then the aggregate should not rely on the handler to remember it.&lt;/p&gt;
&lt;h3 id=&quot;where-this-pattern-can-go-wrong&quot;&gt;Where this pattern can go wrong&lt;/h3&gt;
&lt;p&gt;Like most good patterns, this one becomes dangerous when overused.&lt;/p&gt;
&lt;p&gt;Not every &lt;code&gt;if&lt;/code&gt; statement needs to become a rule object.&lt;br&gt;
Not every workflow needs an entire rules engine.&lt;br&gt;
Not every tiny validation deserves its own abstraction.&lt;/p&gt;
&lt;p&gt;If the business logic is trivial and local, introducing rule classes may create more ceremony than value.&lt;/p&gt;
&lt;p&gt;The pattern shines when the rules are meaningful, reusable, and important enough to deserve a name. If the condition is just a one-off technical check, a plain conditional may still be the better choice.&lt;/p&gt;
&lt;p&gt;The goal is not abstraction for its own sake. The goal is to make business intent easier to see.&lt;/p&gt;
&lt;h3 id=&quot;why-the-result-pattern-keeps-the-design-honest&quot;&gt;Why the Result pattern keeps the design honest&lt;/h3&gt;
&lt;p&gt;The Result pattern adds a second layer of clarity.&lt;/p&gt;
&lt;p&gt;A failure is no longer hidden behind a thrown exception for something the system fully expected. Instead, the caller gets an explicit outcome. That makes business rejections feel normal rather than exceptional, which is often the right model for application workflows. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://enterprisecraftsmanship.com/posts/error-handling-exception-or-result/?utm_source=chatgpt.com&quot; title=&quot;Error handling: Exception or Result?&quot;&gt;Enterprise Craftsmanship&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;When paired with rules, the flow becomes very natural:&lt;/p&gt;
&lt;p&gt;Evaluate the business policy.&lt;br&gt;
If it fails, return a failure result.&lt;br&gt;
If it passes, continue the operation.&lt;/p&gt;
&lt;p&gt;That is simple, predictable, and easy to test.&lt;/p&gt;
&lt;h3 id=&quot;final-thought&quot;&gt;Final thought&lt;/h3&gt;
&lt;p&gt;The Rule pattern is one of those ideas that looks modest at first, but pays off more and more as the codebase grows.&lt;/p&gt;
&lt;p&gt;It helps you name business policies.&lt;br&gt;
It helps you reuse them.&lt;br&gt;
It helps you combine them.&lt;br&gt;
And when paired with the Result pattern, it gives your application a very clean way to both enforce rules and communicate outcomes. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://martinfowler.com/apsupp/spec.pdf?utm_source=chatgpt.com&quot; title=&quot;Specifications&quot;&gt;martinfowler.com&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;If your handlers are starting to fill up with business conditionals, this pattern is often a strong sign that the code wants a better language.&lt;/p&gt;
&lt;p&gt;And that, more than anything else, is what good domain design is really about.&lt;/p&gt;
&lt;p&gt;Source code :&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/stevsharp/RulePatternApplication&quot;&gt;https://github.com/stevsharp/RulePatternApplication&lt;/a&gt;&lt;/p&gt;
&lt;h3 id=&quot;references&quot;&gt;References&lt;/h3&gt;
&lt;p&gt;Martin Fowler, &lt;em&gt;Specifications&lt;/em&gt;. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://martinfowler.com/apsupp/spec.pdf?utm_source=chatgpt.com&quot; title=&quot;Specifications&quot;&gt;martinfowler.com&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;Microsoft Learn, &lt;em&gt;Designing validations in the domain model layer&lt;/em&gt;. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-model-layer-validations?utm_source=chatgpt.com&quot; title=&quot;Designing validations in the domain model layer - .NET&quot;&gt;Microsoft Learn&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;Microsoft Learn, &lt;em&gt;Designing a DDD-oriented microservice&lt;/em&gt;. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/ddd-oriented-microservice?utm_source=chatgpt.com&quot; title=&quot;Designing a DDD-oriented microservice - .NET&quot;&gt;Microsoft Learn&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;Vladimir Khorikov, &lt;em&gt;Error handling: Exception or Result?&lt;/em&gt; (&lt;a rel=&quot;nofollow&quot; href=&quot;https://enterprisecraftsmanship.com/posts/error-handling-exception-or-result/?utm_source=chatgpt.com&quot; title=&quot;Error handling: Exception or Result?&quot;&gt;Enterprise Craftsmanship&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;Vladimir Khorikov, &lt;em&gt;Advanced error handling techniques&lt;/em&gt;. (&lt;a rel=&quot;nofollow&quot; href=&quot;https://enterprisecraftsmanship.com/posts/advanced-error-handling-techniques/?utm_source=chatgpt.com&quot; title=&quot;Advanced error handling techniques&quot;&gt;Enterprise Craftsmanship&lt;/a&gt;)&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/14143/the-rule-pattern-in-c-and-why-it-works-so-well-with-the-result-pattern</guid>
<pubDate>Tue, 07 Apr 2026 10:01:22 +0000</pubDate>
</item>
<item>
<title>ASP.NET Core Custom Logger — Save Logs to Database (SQL)</title>
<link>https://coderlegion.com/10763/asp-net-core-custom-logger-save-logs-to-database-sql</link>
<description>&lt;p&gt;&lt;strong&gt;ASP.NET Core&lt;/strong&gt; already gives you solid logging out of the box, and if you want richer sinks and structured logs, Serilog is a common choice.&lt;/p&gt;
&lt;p&gt;But sometimes you cannot use a ready made sink, because the company already has a legacy logging table with a fixed schema. In that case, you build a custom database logger that writes into that table.&lt;/p&gt;
&lt;p&gt;This tutorial includes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Database table&lt;/li&gt;
&lt;li&gt;Logger options&lt;/li&gt;
&lt;li&gt;Custom logger&lt;/li&gt;
&lt;li&gt;Logger provider&lt;/li&gt;
&lt;li&gt;Background queue (Channel)&lt;/li&gt;
&lt;li&gt;Dapper SQL insert&lt;/li&gt;
&lt;li&gt;Registration in Program.cs&lt;/li&gt;
&lt;li&gt;Usage example&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;1-create-the-sql-table&quot;&gt;1️⃣ Create the SQL table&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;CREATE TABLE dbo.AppLogs
(
    LogId     BIGINT IDENTITY PRIMARY KEY,
    Ts        DATETIME2(3) NOT NULL,
    Level     NVARCHAR(20) NOT NULL,
    Category  NVARCHAR(200) NOT NULL,
    TraceId   NVARCHAR(64) NULL,
    Message   NVARCHAR(MAX) NOT NULL,
    Exception NVARCHAR(MAX) NULL,
    Scopes    NVARCHAR(MAX) NULL
);

CREATE INDEX IX_AppLogs_Ts    ON dbo.AppLogs(Ts);
CREATE INDEX IX_AppLogs_Level ON dbo.AppLogs(Level);
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;2-add-nuget-packages&quot;&gt;2️⃣ Add NuGet packages&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;dotnet add package Dapper
dotnet add package Microsoft.Data.SqlClient
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;3-logger-options&quot;&gt;3️⃣ Logger options&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;public sealed class DbLogOptions
{
    public string ConnectionString { get; set; } = string.Empty;
    public LogLevel MinLevel { get; set; } = LogLevel.Information;

    // Max number of log entries waiting in memory
    public int MaxQueue { get; set; } = 5000;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;4-log-entry-model&quot;&gt;4️⃣ Log entry model&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;public sealed class DbLogEntry
{
    public DateTime Ts { get; set; }
    public string Level { get; set; } = &quot;&quot;;
    public string Category { get; set; } = &quot;&quot;;
    public string? TraceId { get; set; }
    public string Message { get; set; } = &quot;&quot;;
    public string? Exception { get; set; }
    public string? Scopes { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;5-custom-database-logger&quot;&gt;5️⃣ Custom database logger&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;using System.Diagnostics;
using System.Text.Json;
using System.Threading.Channels;
using Microsoft.Extensions.Logging;

public sealed class DbLogger : ILogger
{
    private readonly string _category;
    private readonly DbLogOptions _options;
    private readonly Channel&amp;lt;DbLogEntry&amp;gt; _channel;
    private readonly IExternalScopeProvider? _scopeProvider;

    public DbLogger(
        string category,
        DbLogOptions options,
        Channel&amp;lt;DbLogEntry&amp;gt; channel,
        IExternalScopeProvider? scopeProvider)
    {
        _category = category;
        _options = options;
        _channel = channel;
        _scopeProvider = scopeProvider;
    }

    public IDisposable BeginScope&amp;lt;TState&amp;gt;(TState state) =&amp;gt;
        _scopeProvider?.Push(state) ?? NullScope.Instance;

    public bool IsEnabled(LogLevel logLevel) =&amp;gt; logLevel &amp;gt;= _options.MinLevel;

    public void Log&amp;lt;TState&amp;gt;(
        LogLevel logLevel,
        EventId eventId,
        TState state,
        Exception? exception,
        Func&amp;lt;TState, Exception?, string&amp;gt; formatter)
    {
        if (!IsEnabled(logLevel)) return;
        if (formatter is null) return;

        var traceId = Activity.Current?.TraceId.ToString();

        string? scopesJson = null;
        if (_scopeProvider is not null)
        {
            var scopes = new List&amp;lt;object?&amp;gt;();
            _scopeProvider.ForEachScope((s, list) =&amp;gt; list.Add(s), scopes);

            if (scopes.Count &amp;gt; 0)
                scopesJson = JsonSerializer.Serialize(scopes);
        }

        var entry = new DbLogEntry
        {
            Ts = DateTime.UtcNow,
            Level = logLevel.ToString(),
            Category = _category,
            TraceId = traceId,
            Message = formatter(state, exception),
            Exception = exception?.ToString(),
            Scopes = scopesJson
        };

        // If queue is full, this returns false and the log is dropped
        _ = _channel.Writer.TryWrite(entry);
    }

    private sealed class NullScope : IDisposable
    {
        public static readonly NullScope Instance = new();
        public void Dispose() { }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;6-logger-provider-writes-to-sql-using-dapper-&quot;&gt;6️⃣ Logger provider (writes to SQL using Dapper)&lt;/h3&gt;
&lt;p&gt;This provider uses a bounded channel and a single background reader so request threads never block on SQL.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;using System.Threading.Channels;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

public sealed class DbLoggerProvider : ILoggerProvider, ISupportExternalScope
{
    private readonly DbLogOptions _options;
    private readonly Channel&amp;lt;DbLogEntry&amp;gt; _channel;
    private readonly CancellationTokenSource _cts = new();
    private IExternalScopeProvider? _scopeProvider;

    public DbLoggerProvider(IOptions&amp;lt;DbLogOptions&amp;gt; options)
    {
        _options = options.Value;

        var channelOptions = new BoundedChannelOptions(_options.MaxQueue)
        {
            SingleReader = true,
            SingleWriter = false,
            FullMode = BoundedChannelFullMode.DropOldest
        };

        _channel = Channel.CreateBounded&amp;lt;DbLogEntry&amp;gt;(channelOptions);

        _ = Task.Run(ProcessQueueAsync);
    }

    public ILogger CreateLogger(string categoryName) =&amp;gt;
        new DbLogger(categoryName, _options, _channel, _scopeProvider);

    public void SetScopeProvider(IExternalScopeProvider scopeProvider) =&amp;gt;
        _scopeProvider = scopeProvider;

    public void Dispose()
    {
        _cts.Cancel();
        _channel.Writer.TryComplete();
        _cts.Dispose();
    }

    private async Task ProcessQueueAsync()
    {
        const string sql = @&quot;
INSERT INTO dbo.AppLogs (Ts, Level, Category, TraceId, Message, Exception, Scopes)
VALUES (@Ts, @Level, @Category, @TraceId, @Message, @Exception, @Scopes);&quot;;

        try
        {
            while (await _channel.Reader.WaitToReadAsync(_cts.Token))
            {
                while (_channel.Reader.TryRead(out var entry))
                {
                    await using var conn = new SqlConnection(_options.ConnectionString);
                    await conn.ExecuteAsync(sql, entry);
                }
            }
        }
        catch (OperationCanceledException)
        {
            // graceful shutdown
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;7-add-registration-extension&quot;&gt;7️⃣ Add registration extension&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

public static class DbLoggerExtensions
{
    public static ILoggingBuilder AddDbLogger(
        this ILoggingBuilder builder,
        Action&amp;lt;DbLogOptions&amp;gt; configure)
    {
        builder.Services.Configure(configure);
        builder.Services.AddSingleton&amp;lt;ILoggerProvider, DbLoggerProvider&amp;gt;();
        return builder;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;8-register-in-program-cs&quot;&gt;8️⃣ Register in Program.cs&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;var builder = WebApplication.CreateBuilder(args);

builder.Logging.ClearProviders();
builder.Logging.AddConsole();

builder.Logging.AddDbLogger(options =&amp;gt;
{
    options.ConnectionString = builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)!;
    options.MinLevel = LogLevel.Information;
    options.MaxQueue = 5000;
});

var app = builder.Build();

app.MapGet(&quot;/test&quot;, (ILogger&amp;lt;Program&amp;gt; logger) =&amp;gt;
{
    logger.LogInformation(&quot;Hello from DB Logger&quot;);
    logger.LogError(new Exception(&quot;Test&quot;), &quot;Something failed&quot;);
    return Results.Ok(&quot;OK&quot;);
});

app.Run();
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;why-we-used-channels-in-the-db-logger&quot;&gt;Why we used Channels in the DB logger&lt;/h3&gt;
&lt;p&gt;Your logger needs to accept logs from many producers (web requests, background jobs, services) and write them to the DB via one efficient writer without blocking request threads or losing control when traffic spikes. Channels are a great fit:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Non blocking producers&lt;/li&gt;
&lt;li&gt;Backpressure with bounded capacity&lt;/li&gt;
&lt;li&gt;Single reader, many writers&lt;/li&gt;
&lt;li&gt;Async, allocation friendly&lt;/li&gt;
&lt;li&gt;Graceful shutdown&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Source code:&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/stevsharp/DbLoggerSample&quot;&gt;https://github.com/stevsharp/DbLoggerSample&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/10763/asp-net-core-custom-logger-save-logs-to-database-sql</guid>
<pubDate>Fri, 30 Jan 2026 09:30:43 +0000</pubDate>
</item>
<item>
<title>SQL Server and Azure SQL Updates with EF Core 10</title>
<link>https://coderlegion.com/9100/sql-server-and-azure-sql-updates-with-ef-core-10</link>
<description>&lt;p&gt;EF Core 10 was released in November 2025 together with .NET 10 and is an LTS release supported until 2028. This version mainly focuses on better alignment with new SQL Server capabilities rather than introducing radically new concepts.&lt;/p&gt;
&lt;p&gt;Below are a few changes that are worth noting from a practical point of view.&lt;/p&gt;
&lt;h3 id=&quot;vector-data-type-support&quot;&gt;Vector data type support&lt;/h3&gt;
&lt;p&gt;EF Core 10 adds direct support for the &lt;strong&gt;vector&lt;/strong&gt; data type introduced in SQL Server 2025 and Azure SQL. This makes it possible to store embeddings directly in the database without additional workarounds.&lt;/p&gt;
&lt;p&gt;A simple entity example looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;public class Blog
{
    public int Id { get; set; }

    [Column(TypeName = &quot;vector(1536)&quot;)]
    public SqlVector&amp;lt;float&amp;gt; Embedding { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Once the embedding is generated on the application side, it can be saved using the standard EF workflow:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;context.Blogs.Add(new Blog
{
    Embedding = new SqlVector&amp;lt;float&amp;gt;(embedding)
});

await context.SaveChangesAsync();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Similarity queries can also be written directly in LINQ using &lt;code&gt;EF.Functions.VectorDistance&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;var blogs = await context.Blogs
    .OrderBy(b =&amp;gt; EF.Functions.VectorDistance(&quot;cosine&quot;, b.Embedding, queryVector))
    .Take(3)
    .ToListAsync();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is useful in scenarios such as semantic search or basic recommendation logic, without needing custom SQL or external query layers.&lt;/p&gt;
&lt;h3 id=&quot;native-json-data-type-mapping&quot;&gt;Native JSON data type mapping&lt;/h3&gt;
&lt;p&gt;With SQL Server 2025, JSON can now be stored using a dedicated &lt;strong&gt;json&lt;/strong&gt; data type. EF Core 10 supports this natively and uses it automatically when the compatibility level allows it.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;public class Blog
{
    public int Id { get; set; }
    public string[] Tags { get; set; }
    public BlogDetails Details { get; set; }
}

public class BlogDetails
{
    public int Viewers { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Model configuration:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;modelBuilder.Entity&amp;lt;Blog&amp;gt;()
    .ComplexProperty(b =&amp;gt; b.Details, b =&amp;gt; b.ToJson());
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With this setup, both &lt;code&gt;Tags&lt;/code&gt; and &lt;code&gt;Details&lt;/code&gt; are created as &lt;code&gt;json&lt;/code&gt; columns in the database.&lt;/p&gt;
&lt;p&gt;Querying remains straightforward:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;var blogs = await context.Blogs
    .Where(b =&amp;gt; b.Details.Viewers &amp;gt; 3)
    .ToListAsync();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;EF Core translates this into SQL using the appropriate JSON functions. For domains that already rely on JSON-like structures, this results in cleaner models and fewer mapping concerns.&lt;/p&gt;
&lt;h3 id=&quot;naming-default-constraints&quot;&gt;Naming default constraints&lt;/h3&gt;
&lt;p&gt;EF Core 10 allows explicitly naming default constraints instead of relying on database-generated names. This can help reduce unnecessary changes in migrations and make schema updates easier to track.&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;modelBuilder.Entity&amp;lt;Post&amp;gt;()
    .Property(p =&amp;gt; p.CreatedDate)
    .HasDefaultValueSql(&quot;GETDATE()&quot;, &quot;DF_Post_CreatedDate&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It’s also possible to enable automatic naming across the model:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;modelBuilder.UseNamedDefaultConstraints();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This change is mostly about maintainability, especially in projects with long migration histories.&lt;/p&gt;
&lt;h3 id=&quot;closing-thoughts&quot;&gt;Closing thoughts&lt;/h3&gt;
&lt;p&gt;EF Core 10 feels like a refinement release rather than a disruptive one. The added support for vector and JSON data types mainly improves how EF integrates with newer SQL Server features, while smaller changes like constraint naming help with long-term maintenance.&lt;/p&gt;
</description>
<category>Web Dev</category>
<guid isPermaLink="true">https://coderlegion.com/9100/sql-server-and-azure-sql-updates-with-ef-core-10</guid>
<pubDate>Tue, 30 Dec 2025 21:06:54 +0000</pubDate>
</item>
<item>
<title>️ From Spaghetti to Scalable: Refactoring a Legacy .NET App Architecture</title>
<link>https://coderlegion.com/7633/from-spaghetti-to-scalable-refactoring-a-legacy-net-app-architecture</link>
<description>&lt;p&gt;Every developer eventually inherits a legacy .NET project the kind where every method talks to everything, and a single change breaks three other features. &lt;/p&gt;
&lt;p&gt;We had one of those too. And instead of rewriting from scratch, we decided to refactor and evolve it step by step. Here’s what made the difference &lt;/p&gt;
&lt;p&gt; &lt;strong&gt;Started with understanding, not rewriting&lt;/strong&gt;.&lt;br&gt;
We mapped dependencies and identified the real pain points before touching a single line of code.&lt;/p&gt;
&lt;p&gt; &lt;strong&gt;Introduced layers gradually&lt;/strong&gt;.&lt;br&gt;
Added separation between API, business logic, and data layers — even if it wasn’t “perfect” at first.&lt;/p&gt;
&lt;p&gt; &lt;strong&gt;Applied Dependency Injection&lt;/strong&gt;.&lt;br&gt;
Breaking hard-coded dependencies gave us flexibility and made testing possible for the first time.&lt;/p&gt;
&lt;p&gt; &lt;strong&gt;Moved toward Clean Architecture&lt;/strong&gt;.&lt;br&gt;
Organized the solution around use cases and domain logic, not around technical layers.&lt;/p&gt;
&lt;p&gt; &lt;strong&gt;Incremental refactoring &amp;gt; big bang rewrites&lt;/strong&gt;.&lt;br&gt;
We refactored feature by feature while keeping the app running — zero downtime.&lt;/p&gt;
&lt;p&gt; &lt;strong&gt;Added automated tests along the way.&lt;/strong&gt;&lt;br&gt;
Unit tests became our safety net for each refactored module.&lt;/p&gt;
&lt;p&gt; &lt;strong&gt;Introduced modern tools gradually&lt;/strong&gt;.&lt;br&gt;
Switched to EF Core, MediatR, and background jobs via Hangfire — one at a time.&lt;/p&gt;
&lt;p&gt;After months of iteration, we transformed a fragile legacy system into a modular, testable, and scalable architecture — without losing business continuity.&lt;/p&gt;
&lt;p&gt; Have you ever refactored a legacy .NET project? What approach worked best for you?&lt;/p&gt;
&lt;h2 id=&quot;dotnet-softwarearchitecture-refactoring-cleanarchitecture-csharp-softwareengineering-backend-devleadership-legacycode&quot;&gt;dotnet #softwarearchitecture #refactoring #cleanarchitecture #csharp #softwareengineering #backend #devleadership #legacycode&lt;/h2&gt;
</description>
<category>Backend Dev</category>
<guid isPermaLink="true">https://coderlegion.com/7633/from-spaghetti-to-scalable-refactoring-a-legacy-net-app-architecture</guid>
<pubDate>Sat, 22 Nov 2025 20:34:12 +0000</pubDate>
</item>
<item>
<title>Tutorial: Building a .NET 9 Console App with Hangfire and Channels</title>
<link>https://coderlegion.com/7559/tutorial-building-a-net-9-console-app-with-hangfire-and-channels</link>
<description>&lt;h2 id=&quot;tutorial-building-a-net-9-console-app-with-hangfire-and-channels&quot;&gt;Tutorial: Building a .NET 9 Console App with Hangfire and Channels&lt;/h2&gt;
&lt;h3 id=&quot;overview&quot;&gt;Overview&lt;/h3&gt;
&lt;p&gt;In this tutorial, you will build a .NET 8 console application that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Polls data from an API, or simulates it&lt;/li&gt;
&lt;li&gt;Uses &lt;strong&gt;System.Threading.Channels&lt;/strong&gt; for producer consumer messaging&lt;/li&gt;
&lt;li&gt;Runs background tasks using &lt;strong&gt;Hosted Services&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Enqueues jobs in &lt;strong&gt;Hangfire&lt;/strong&gt; using in memory storage&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;why-use-system-threading-channels&quot;&gt;Why Use System.Threading.Channels&lt;/h3&gt;
&lt;p&gt;Traditional producer consumer patterns often rely on &lt;strong&gt;BlockingCollection&lt;/strong&gt; or custom queues, which can introduce:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Thread contention&lt;/li&gt;
&lt;li&gt;Blocking calls&lt;/li&gt;
&lt;li&gt;Complex synchronization&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;code&gt;System.Threading.Channels&lt;/code&gt; provides:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Asynchronous, non blocking communication between producers and consumers&lt;/li&gt;
&lt;li&gt;Built in backpressure when using bounded channels&lt;/li&gt;
&lt;li&gt;High performance with low allocation&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In this app:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;DataPollingService&lt;/strong&gt; is the producer, it writes work items into the channel&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;ChannelConsumerService&lt;/strong&gt; is the consumer, it reads items and enqueues Hangfire jobs&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;why-hosted-services&quot;&gt;Why Hosted Services&lt;/h3&gt;
&lt;p&gt;Hosted services, &lt;code&gt;BackgroundService&lt;/code&gt;, integrate with the .NET Generic Host. You get:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Graceful lifecycle management, start and stop&lt;/li&gt;
&lt;li&gt;Dependency injection&lt;/li&gt;
&lt;li&gt;Logging and configuration&lt;/li&gt;
&lt;li&gt;Non blocking background loops&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This app uses two hosted services:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;DataPollingService&lt;/code&gt; simulates fetching data and writes work items to the channel&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ChannelConsumerService&lt;/code&gt; reads from the channel and enqueues Hangfire jobs&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;what-is-backgroundservice&quot;&gt;What is &lt;code&gt;BackgroundService&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;BackgroundService&lt;/code&gt; is a base class that implements &lt;code&gt;IHostedService&lt;/code&gt; and gives you a long running &lt;code&gt;ExecuteAsync&lt;/code&gt; loop. It plugs into the Generic Host, so you get DI, logging, and coordinated shutdown.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Use cases&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Poll APIs or message brokers&lt;/li&gt;
&lt;li&gt;Drain a queue or channel&lt;/li&gt;
&lt;li&gt;Run internal maintenance tasks&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Key points&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Use &lt;code&gt;ExecuteAsync(CancellationToken)&lt;/code&gt; as your main loop&lt;/li&gt;
&lt;li&gt;Respect the cancellation token for fast shutdown&lt;/li&gt;
&lt;li&gt;Prefer &lt;code&gt;PeriodicTimer&lt;/code&gt; over &lt;code&gt;Task.Delay&lt;/code&gt; in recurring loops&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;what-is-hangfire&quot;&gt;What is Hangfire&lt;/h3&gt;
&lt;p&gt;Hangfire is a background job processor for .NET. You enqueue a method call, Hangfire persists and executes it with workers. It supports fire and forget, delayed, recurring, continuations, and batches.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why it helps here&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The consumer stays lightweight, it only enqueues work&lt;/li&gt;
&lt;li&gt;Processing is retried and observable with a dashboard&lt;/li&gt;
&lt;li&gt;You can swap storage later for durability&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Common job types&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Fire and forget, &lt;code&gt;BackgroundJob.Enqueue(() =&amp;gt; DoWork())&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Delayed, &lt;code&gt;BackgroundJob.Schedule(() =&amp;gt; DoWork(), TimeSpan.FromMinutes(5))&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Recurring, &lt;code&gt;RecurringJob.AddOrUpdate(&quot;nightly&quot;, () =&amp;gt; DoWork(), &quot;0 2 * * *&quot;)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Notes, in memory storage is fine for demos, not for production. Jobs should be idempotent.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;what-is-system-threading-channels&quot;&gt;What is &lt;code&gt;System.Threading.Channels&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Channels are high performance, async friendly, in process queues. You get a &lt;code&gt;ChannelWriter&amp;lt;T&amp;gt;&lt;/code&gt; for producers and a &lt;code&gt;ChannelReader&amp;lt;T&amp;gt;&lt;/code&gt; for consumers. Channels work with &lt;code&gt;async&lt;/code&gt; and &lt;code&gt;IAsyncEnumerable&amp;lt;T&amp;gt;&lt;/code&gt;, and avoid blocking threads.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why they shine&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Async reads and writes&lt;/li&gt;
&lt;li&gt;Bounded channels provide backpressure&lt;/li&gt;
&lt;li&gt;Options like &lt;code&gt;SingleReader&lt;/code&gt; and &lt;code&gt;SingleWriter&lt;/code&gt; reduce overhead when true&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Fast read loop&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;while (await reader.WaitToReadAsync(ct))
    while (reader.TryRead(out var item))
        await HandleAsync(item, ct);
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;steps-to-build&quot;&gt;Steps to Build&lt;/h3&gt;
&lt;h4 id=&quot;1-create-the-project&quot;&gt;1. Create the Project&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;dotnet new console -n CustomerSyncConsole
cd CustomerSyncConsole
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;2-add-nuget-packages-1&quot;&gt;2. Add NuGet Packages&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;dotnet add package Hangfire
dotnet add package Hangfire.MemoryStorage
dotnet add package Microsoft.Extensions.Hosting
dotnet add package Microsoft.Extensions.Logging.Console
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;3-implement-the-code&quot;&gt;3. Implement the Code&lt;/h4&gt;
&lt;p&gt;Below is a complete &lt;code&gt;Program.cs&lt;/code&gt; with comments. It uses an unbounded channel for simplicity. See the optional bounded channel section that follows if you want backpressure.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;using System.Threading.Channels;
using Hangfire;
using Hangfire.MemoryStorage;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace CustomerSyncConsole;

public sealed record CustomerWorkItem(int CustomerId, string PayloadId, DateTimeOffset ReceivedAt, string RawJson);

public interface ICustomerJobs
{
    Task ProcessCustomer(int customerId, string payloadId, CancellationToken ct = default);
}

public sealed class CustomerJobs(ILogger&amp;lt;CustomerJobs&amp;gt; logger) : ICustomerJobs
{
    private readonly ILogger&amp;lt;CustomerJobs&amp;gt; _logger = logger;

    public async Task ProcessCustomer(int customerId, string payloadId, CancellationToken ct = default)
    {
        _logger.LogInformation(&quot;Hangfire job started for Customer {CustomerId}, Payload {PayloadId}&quot;, customerId, payloadId);
        await Task.Delay(TimeSpan.FromSeconds(2), ct);
        _logger.LogInformation(&quot;Hangfire job completed for Customer {CustomerId}, Payload {PayloadId}&quot;, customerId, payloadId);
    }
}

public interface IStorage
{
    Task SaveAsync(string payloadId, string rawJson, CancellationToken ct);
}

public sealed class InMemoryStorage(ILogger&amp;lt;InMemoryStorage&amp;gt; logger) : IStorage
{
    private readonly ILogger&amp;lt;InMemoryStorage&amp;gt; _logger = logger;
    private readonly Dictionary&amp;lt;string, string&amp;gt; _store = new();

    public Task SaveAsync(string payloadId, string rawJson, CancellationToken ct)
    {
        _store[payloadId] = rawJson;
        _logger.LogInformation(&quot;Saved payload {PayloadId} in-memory (size={Size}).&quot;, payloadId, _store.Count);
        return Task.CompletedTask;
    }
}

public sealed class DataPollingService(
    ILogger&amp;lt;DataPollingService&amp;gt; logger,
    Channel&amp;lt;CustomerWorkItem&amp;gt; channel,
    IConfiguration config,
    IStorage storage) : BackgroundService
{
    private readonly ILogger&amp;lt;DataPollingService&amp;gt; _logger = logger;
    private readonly ChannelWriter&amp;lt;CustomerWorkItem&amp;gt; _writer = channel.Writer;
    private readonly IConfiguration _config = config;
    private readonly IStorage _storage = storage;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var intervalSeconds = _config.GetValue(&quot;Polling:IntervalSeconds&quot;, 10);
        var timer = new PeriodicTimer(TimeSpan.FromSeconds(intervalSeconds));

        _logger.LogInformation(&quot;Polling started. Interval={Interval}s&quot;, intervalSeconds);

        try
        {
            while (await timer.WaitForNextTickAsync(stoppingToken))
            {
                var simulated = new[]
                {
                    new IncomingDto { CustomerId = 1, PayloadId = Guid.NewGuid().ToString(&quot;N&quot;) },
                    new IncomingDto { CustomerId = 2, PayloadId = Guid.NewGuid().ToString(&quot;N&quot;) },
                };

                foreach (var dto in simulated)
                {
                    var raw = System.Text.Json.JsonSerializer.Serialize(dto);
                    await _storage.SaveAsync(dto.PayloadId, raw, stoppingToken);

                    var item = new CustomerWorkItem(dto.CustomerId, dto.PayloadId, DateTimeOffset.UtcNow, raw);
                    await _writer.WriteAsync(item, stoppingToken);
                    _logger.LogInformation(&quot;Queued work item for Customer {CustomerId}, Payload {PayloadId}&quot;, dto.CustomerId, dto.PayloadId);
                }
            }
        }
        finally
        {
            _writer.TryComplete();
        }
    }

    private sealed class IncomingDto
    {
        public int CustomerId { get; set; }
        public string PayloadId { get; set; } = Guid.NewGuid().ToString(&quot;N&quot;);
    }
}

public sealed class ChannelConsumerService(
    Channel&amp;lt;CustomerWorkItem&amp;gt; channel,
    IBackgroundJobClient backgroundJobClient,
    ILogger&amp;lt;ChannelConsumerService&amp;gt; logger) : BackgroundService
{
    private readonly ChannelReader&amp;lt;CustomerWorkItem&amp;gt; _reader = channel.Reader;
    private readonly IBackgroundJobClient _backgroundJobClient = backgroundJobClient;
    private readonly ILogger&amp;lt;ChannelConsumerService&amp;gt; _logger = logger;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation(&quot;Channel consumer started.&quot;);
        await foreach (var item in _reader.ReadAllAsync(stoppingToken))
        {
            if (item.CustomerId == 1)
            {
                var jobId = _backgroundJobClient.Enqueue&amp;lt;ICustomerJobs&amp;gt;(job =&amp;gt; job.ProcessCustomer(item.CustomerId, item.PayloadId, CancellationToken.None));
                _logger.LogInformation(&quot;Enqueued Hangfire job {JobId} for Customer {CustomerId}, Payload {PayloadId}&quot;, jobId, item.CustomerId, item.PayloadId);
            }
        }
        _logger.LogInformation(&quot;Channel consumer stopping.&quot;);
    }
}

public static class Program
{
    public static async Task Main(string[] args)
    {
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(cfg =&amp;gt;
            {
                cfg.AddInMemoryCollection(new Dictionary&amp;lt;string, string?&amp;gt;
                {
                    [&quot;Polling:IntervalSeconds&quot;] = &quot;10&quot;
                });
            })
            .ConfigureLogging(logging =&amp;gt;
            {
                logging.ClearProviders();
                logging.AddSimpleConsole(o =&amp;gt;
                {
                    o.TimestampFormat = &quot;HH:mm:ss &quot;;
                    o.SingleLine = true;
                });
                logging.SetMinimumLevel(LogLevel.Information);
            })
            .ConfigureServices((ctx, services) =&amp;gt;
            {
                // Unbounded for simplicity in this tutorial
                services.AddSingleton(Channel.CreateUnbounded&amp;lt;CustomerWorkItem&amp;gt;());

                // Hangfire in memory
                services.AddHangfire(config =&amp;gt; config.UseMemoryStorage());
                services.AddHangfireServer();

                services.AddSingleton&amp;lt;ICustomerJobs, CustomerJobs&amp;gt;();
                services.AddSingleton&amp;lt;IStorage, InMemoryStorage&amp;gt;();
                services.AddHostedService&amp;lt;DataPollingService&amp;gt;();
                services.AddHostedService&amp;lt;ChannelConsumerService&amp;gt;();
            })
            .Build();

        await host.RunAsync();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;optional-switch-to-a-bounded-channel&quot;&gt;Optional, switch to a bounded channel&lt;/h3&gt;
&lt;p&gt;For services that can receive spikes, prefer bounded channels to get backpressure.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;services.AddSingleton(_ =&amp;gt;
{
    var opts = new BoundedChannelOptions(capacity: 512)
    {
        FullMode = BoundedChannelFullMode.Wait,
        SingleReader = true,   // one consumer service
        SingleWriter = true    // one producer service
    };
    return Channel.CreateBounded&amp;lt;CustomerWorkItem&amp;gt;(opts);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Replace the unbounded registration with the code above.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;best-practices&quot;&gt;Best Practices&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Pass &lt;code&gt;CancellationToken&lt;/code&gt; to every &lt;code&gt;WriteAsync&lt;/code&gt; and &lt;code&gt;ReadAllAsync&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Complete the writer during shutdown, then await reader completion&lt;/li&gt;
&lt;li&gt;Make Hangfire jobs idempotent, retries can occur&lt;/li&gt;
&lt;li&gt;Consider persistent Hangfire storage for real workloads, for example SQL Server or SQLite&lt;/li&gt;
&lt;li&gt;Expose channel depth as a metric if you need visibility, current size versus capacity&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;run-it&quot;&gt;Run it&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;dotnet run
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You should see logs from both services. The producer writes items into the channel. The consumer enqueues Hangfire jobs for customer 1. The Hangfire server executes those jobs.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;references-1&quot;&gt;References&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/stevsharp/CustomerJobRunner&quot;&gt;Source Code&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/dotnet/api/system.threading.channels&quot;&gt;System.Threading.Channels Documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/aspnet/core/fundamentals/host/hosted-services&quot;&gt;BackgroundService and Hosted Services in .NET&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.hangfire.io/&quot;&gt;Hangfire Official Documentation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Getting Started</category>
<guid isPermaLink="true">https://coderlegion.com/7559/tutorial-building-a-net-9-console-app-with-hangfire-and-channels</guid>
<pubDate>Thu, 20 Nov 2025 07:56:42 +0000</pubDate>
</item>
<item>
<title>Global Exception Handler vs Custom Middleware in ASP.NET Core</title>
<link>https://coderlegion.com/7028/global-exception-handler-vs-custom-middleware-in-asp-net-core</link>
<description>&lt;p&gt;&lt;strong&gt;The problem we’re solving&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Stuff goes wrong: timeouts, not-found resources, validation fails. You want one consistent error response and clean logs, without sprinkling try/catch everywhere.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Two good options&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Option A — Global Exception Handler (recommended default)&lt;/p&gt;
&lt;p&gt;Think of it as the framework’s built-in safety net. You plug in one handler and ASP.NET Core turns exceptions into ProblemDetails JSON automatically.&lt;/p&gt;
&lt;p&gt;Why people like it&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Minimal code, fewer edge cases. &lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Plays nice with content negotiation.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;One central place to map exception → HTTP status.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Use when: you want &lt;strong&gt;standard errors&lt;/strong&gt; and consistency across the app.&lt;/p&gt;
&lt;p&gt;Option B — Custom Exception Middleware&lt;/p&gt;
&lt;p&gt;Your own IMiddleware that wraps the pipeline in &lt;strong&gt;try/catch&lt;/strong&gt; and writes whatever JSON shape you want.&lt;/p&gt;
&lt;p&gt;Why people use it&lt;/p&gt;
&lt;p&gt;-Full control over the response body and headers.&lt;/p&gt;
&lt;p&gt;-Easy to keep a legacy “envelope” format.&lt;/p&gt;
&lt;p&gt;-Use when: clients require a specific, non-ProblemDetails format or you need special side effects.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Decision guide&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;-Standard JSON errors and less boilerplate → Global handler&lt;/p&gt;
&lt;p&gt;-Legacy/bespoke response body → Middleware&lt;/p&gt;
&lt;p&gt;-Want a single place to map exceptions to statuses → Global handler&lt;/p&gt;
&lt;p&gt;-Heavy custom logic on errors (headers, counters) → Middleware&lt;/p&gt;
&lt;p&gt;-Using MediatR and want clean handlers → Use a MediatR behavior to log, then rethrow so the global handler shapes the response&lt;/p&gt;
&lt;p&gt;1) Global handler wiring (Program.cs)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;builder.Services.AddExceptionHandler&amp;lt;GlobalExceptionHandler&amp;gt;();

app.UseExceptionHandler(); // put this early in the pipeline
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The handler itself (GlobalExceptionHandler.cs)&lt;/p&gt;
&lt;p&gt;using Microsoft.AspNetCore.Diagnostics;&lt;br&gt;
using Microsoft.AspNetCore.Mvc;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public sealed class GlobalExceptionHandler : IExceptionHandler
{
    private readonly ILogger&amp;lt;GlobalExceptionHandler&amp;gt; _logger;
    private readonly IProblemDetailsService _pds;
    private readonly IHostEnvironment _env;

    public GlobalExceptionHandler(ILogger&amp;lt;GlobalExceptionHandler&amp;gt; logger, IProblemDetailsService pds, IHostEnvironment env)
        =&amp;gt; (_logger, _pds, _env) = (logger, pds, env);

    public async ValueTask&amp;lt;bool&amp;gt; TryHandleAsync(HttpContext http, Exception ex, CancellationToken ct)
    {
        var (status, title) = ex switch
        {
            ValidationException =&amp;gt; (422, &quot;Validation failed&quot;),
            NotFoundException   =&amp;gt; (404, &quot;Not found&quot;),
            UnauthorizedAccessException =&amp;gt; (401, &quot;Unauthorized&quot;),
            TimeoutException    =&amp;gt; (503, &quot;Service unavailable&quot;),
            Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException =&amp;gt; (409, &quot;Concurrency conflict&quot;),
            TaskCanceledException =&amp;gt; (408, &quot;Request timeout&quot;),
            OperationCanceledException =&amp;gt; (StatusCodes.Status499ClientClosedRequest, &quot;Client closed request&quot;),
            HttpRequestException =&amp;gt; (502, &quot;Bad gateway&quot;),
            _ =&amp;gt; (500, &quot;Unexpected error&quot;)
        };

        if (status is 503 or 408) http.Response.Headers.TryAdd(&quot;Retry-After&quot;, &quot;5&quot;);

        http.Response.StatusCode = status;

        var pd = new ProblemDetails
        {
            Status = status,
            Title = title,
            Detail = _env.IsDevelopment() ? ex.Message : null,
            Instance = http.Request.Path
        };
        if (ex is ValidationException ve) pd.Extensions[&quot;errors&quot;] = ve.Errors;

        _logger.LogError(ex, &quot;Unhandled exception -&amp;gt; HTTP {Status}&quot;, status);

        return await _pds.TryWriteAsync(new ProblemDetailsContext
        {
            HttpContext = http,
            ProblemDetails = pd,
            Exception = ex
        });
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Custom middleware skeleton&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public sealed class ExceptionEnvelopeMiddleware : IMiddleware
{
    private readonly ILogger&amp;lt;ExceptionEnvelopeMiddleware&amp;gt; _logger;
    private readonly IHostEnvironment _env;
    public ExceptionEnvelopeMiddleware(ILogger&amp;lt;ExceptionEnvelopeMiddleware&amp;gt; logger, IHostEnvironment env)
        =&amp;gt; (_logger, _env) = (logger, env);

    public async Task InvokeAsync(HttpContext ctx, RequestDelegate next)
    {
        try { await next(ctx); }
        catch (Exception ex)
        {
            if (ctx.Response.HasStarted) throw;
            _logger.LogError(ex, &quot;Unhandled exception&quot;);

            ctx.Response.Clear();
            ctx.Response.StatusCode = ex switch
            {
                ValidationException =&amp;gt; StatusCodes.Status422UnprocessableEntity,
                NotFoundException   =&amp;gt; StatusCodes.Status404NotFound,
                TimeoutException    =&amp;gt; StatusCodes.Status503ServiceUnavailable,
                _ =&amp;gt; StatusCodes.Status500InternalServerError
            };
            ctx.Response.ContentType = &quot;application/json&quot;;

            var body = new
            {
                title = ctx.Response.StatusCode == 422 ? &quot;Validation failed&quot; :
                        ctx.Response.StatusCode == 404 ? &quot;Not found&quot; :
                        ctx.Response.StatusCode == 503 ? &quot;Service unavailable&quot; : &quot;Unexpected error&quot;,
                status = ctx.Response.StatusCode,
                traceId = ctx.TraceIdentifier,
                detail = _env.IsDevelopment() ? ex.Message : null,
                errors = ex is ValidationException ve ? ve.Errors : null
            };
            await ctx.Response.WriteAsJsonAsync(body);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Using MediatR? Add a behavior&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;using MediatR;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public sealed class UnhandledExceptionBehavior&amp;lt;TRequest,TResponse&amp;gt; : IPipelineBehavior&amp;lt;TRequest,TResponse&amp;gt;
    where TRequest : notnull
{
    private readonly ILogger&amp;lt;UnhandledExceptionBehavior&amp;lt;TRequest,TResponse&amp;gt;&amp;gt; _logger;
    public UnhandledExceptionBehavior(ILogger&amp;lt;UnhandledExceptionBehavior&amp;lt;TRequest,TResponse&amp;gt;&amp;gt; logger) =&amp;gt; _logger = logger;

    public async Task&amp;lt;TResponse&amp;gt; Handle(TRequest request, RequestHandlerDelegate&amp;lt;TResponse&amp;gt; next, CancellationToken ct)
    {
        try { return await next(); }
        catch (Exception ex)
        {
            _logger.LogError(ex, &quot;Unhandled exception in MediatR for {Request}&quot;, typeof(TRequest).Name);
            throw; // let the global handler shape ProblemDetails
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Common pitfalls (and easy wins)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;-Place the handler early. Put UseExceptionHandler() before routing and authorization.&lt;/p&gt;
&lt;p&gt;-Don’t leak stack traces in production. Keep Detail empty unless in Development.&lt;/p&gt;
&lt;p&gt;-Streaming/gRPC: once the response starts, you can’t switch to JSON. Log and stop.&lt;/p&gt;
&lt;p&gt;-Map the big ones: validation → 422, not found → 404, timeouts → 503, concurrency → 409.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you just want clean, predictable errors, use the &lt;strong&gt;global handle&lt;/strong&gt;r and be done. If your clients expect a specific JSON envelope, use a custom middleware. With MediatR, add a behavior to keep handlers tidy and let the handler (or middleware) do the final shaping.&lt;/p&gt;
&lt;p&gt;Further Reading :&lt;/p&gt;
&lt;p&gt;Error handling &amp;amp; ProblemDetails (official docs)&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-9.0&amp;amp;utm_source=chatgpt.com&quot;&gt;Handle errors in ASP.NET Core (overview). &lt;br&gt;
Microsoft Learn&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.exceptionhandlerextensions.useexceptionhandler?view=aspnetcore-9.0&quot;&gt;Handle errors in ASP.NET Core APIs (includes UseExceptionHandler patterns). &lt;br&gt;
Microsoft Learn&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Middleware&lt;/strong&gt; (how it works &amp;amp; how to write your own)&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-9.0&quot;&gt;Middleware fundamentals (ordering, short-circuiting). &lt;br&gt;
Microsoft Learn&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;MediatR pipeline behaviors&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/LuckyPennySoftware/MediatR&quot;&gt;Jimmy Bogard (creator) — pipeline posts &amp;amp; patterns. &lt;br&gt;
Jimmy Bogard&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://fluentvalidation.net/&quot;&gt;FluentValidation in ASP.NET Core (official docs) for a validation behavior that throws a ValidationException. &lt;br&gt;
fluentvalidation.net&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source Code &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/stevsharp?tab=repositories&quot;&gt;https://github.com/stevsharp?tab=repositories&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
</description>
<category>C#</category>
<guid isPermaLink="true">https://coderlegion.com/7028/global-exception-handler-vs-custom-middleware-in-asp-net-core</guid>
<pubDate>Tue, 04 Nov 2025 09:38:14 +0000</pubDate>
</item>
<item>
<title>Hello World! Welcome to the .NET Group!</title>
<link>https://coderlegion.com/5603/hello-world-welcome-to-the-net-group</link>
<description>&lt;h2 id=&quot;hello-world-welcome-to-the-net-group-&quot;&gt;Hello World! Welcome to the .NET Group!&lt;/h2&gt;
&lt;p&gt;We’re excited to have you here! This is a space where you can share, learn, and connect with other developers who love .NET.&lt;/p&gt;
&lt;h3 id=&quot;start-by-saying-hi-&quot;&gt;Start by saying hi!&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Introduce yourself in the comments below&lt;/strong&gt;—tell us your name, what you’re working on, or something fun about yourself. We’d love to get to know you!&lt;/p&gt;
&lt;p&gt;Once you’ve said hi, you can:&lt;/p&gt;
&lt;p&gt;Share your .NET tips or interesting projects.&lt;/p&gt;
&lt;p&gt;Ask questions and get feedback from the community.&lt;/p&gt;
&lt;p&gt;Comment on and support other members’ posts.&lt;/p&gt;
&lt;p&gt;We’re happy you joined the .NET Group and can’t wait to see your contributions. Let’s make this a friendly and helpful place to learn together!&lt;/p&gt;
</description>
<category>Other</category>
<guid isPermaLink="true">https://coderlegion.com/5603/hello-world-welcome-to-the-net-group</guid>
<pubDate>Fri, 26 Sep 2025 04:01:17 +0000</pubDate>
</item>
<item>
<title> Why Records in C# Are Great (and So Nice to Work With)</title>
<link>https://coderlegion.com/2949/why-records-in-c-are-great-and-so-nice-to-work-with</link>
<description>&lt;p&gt;&lt;strong&gt; Why Records in C# Are Great&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you’ve been working with C# lately, you’ve probably encountered records , a feature introduced in C# 9 that many developers have come to love. &lt;/p&gt;
&lt;p&gt;They’re elegant, powerful, and remove a lot of boilerplate when modeling data.&lt;/p&gt;
&lt;p&gt;But what actually makes them great? Here’s why records aren’t just nice , they’re game-changing.&lt;/p&gt;
&lt;p&gt; What Are Records?&lt;/p&gt;
&lt;p&gt;At their core, records are &lt;strong&gt;reference types&lt;/strong&gt; designed for &lt;strong&gt;immutable&lt;/strong&gt; data modeling. Think of them as classes optimized for holding data  with extra features built in.&lt;/p&gt;
&lt;p&gt;You can define a record in two main ways:&lt;/p&gt;
&lt;p&gt;✅ 1. Positional Syntax (Concise and Clean)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public record Person(string FirstName, string LastName);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This one-liner gives you:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Constructor&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Equals(), GetHashCode(), and ToString() overrides&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;init-only properties (immutable)&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Deconstruction support&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Ouaaa...&lt;/p&gt;
&lt;p&gt;In order to implement all that in a regular class, you'd need to write a lot of code  constructors, equality logic, ToString() overrides, and possibly even a deconstructor. &lt;br&gt;
&lt;strong&gt;Records do it all for you, automatically and cleanly.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;✅ 2. Classic Syntax (More Flexible)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public record Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Need mutability? You can use set instead of init, but that sacrifices immutability and &lt;strong&gt;thread safety.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt; What is init?&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;init&lt;/strong&gt; is a special accessor introduced in C# 9 that allows properties to be set only during initialization making them immutable afterward.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var person = new Person { FirstName = &quot;Alice&quot;, LastName = &quot;Green&quot; };
// person.FirstName = &quot;Bob&quot;; ❌ Not allowed
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;✅ Cleaner than readonly fields&lt;br&gt;
✅ Safer than public setters&lt;br&gt;
✅ Perfect for records, DTOs, and configuration objects&lt;/p&gt;
&lt;p&gt; Reference:&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init&quot;&gt;Microsoft Docs – Init-only Setters&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;✅ 1. Value-Based Equality — Finally Done Right&lt;/p&gt;
&lt;p&gt;With classes, equality checks compare references. With records, it's based on content:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var a = new Person(&quot;Alice&quot;, &quot;Smith&quot;);
var b = new Person(&quot;Alice&quot;, &quot;Smith&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Console.WriteLine(a == b); // True ✅&lt;/p&gt;
&lt;p&gt; Reference:&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record&quot;&gt;Microsoft Docs – Records&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;✅ 2. Immutability by Default — and Thread-Safe by Nature&lt;/p&gt;
&lt;p&gt;Records are immutable by default, which leads to safer, more predictable code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var p1 = new Person(&quot;John&quot;, &quot;Doe&quot;);
var p2 = p1 with { FirstName = &quot;Jane&quot; }; // Creates a copy
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And since their state can't be changed after creation, records are thread-safe for read operations — perfect for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Parallel tasks&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Background services&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Blazor state containers&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Event sourcing&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt; Reference:&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/immutability&quot;&gt;Immutability in C#&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;✅ 3. Concise and Readable Code&lt;br&gt;
Records eliminate boilerplate. You define what matters — and the compiler handles the rest.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public record Invoice(string Id, DateTime Date, decimal Amount);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Clean. Lightweight. Clear.&lt;/p&gt;
&lt;p&gt;✅ 4. Deconstruction and Pattern Matching&lt;/p&gt;
&lt;p&gt;Records play perfectly with modern C# features:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var (first, last) = new Person(&quot;Ana&quot;, &quot;Lopez&quot;);

if (p1 is { FirstName: &quot;John&quot; })
{
    Console.WriteLine(&quot;Hello John!&quot;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt; Reference:&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching&quot;&gt;Pattern Matching in C#&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;✅ 5. Functional Programming Friendly&lt;/p&gt;
&lt;p&gt;Records align with functional principles:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;No side effects&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Easy transformations&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Clear data flow&lt;/p&gt;
&lt;p&gt; var updatedInvoice = invoice with { Amount = invoice.Amount + 10 };&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt; Reference:&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#records&quot;&gt;Welcome to C# 9 – Records&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;✅ 6. Supports Inheritance, Structs, and More&lt;/p&gt;
&lt;p&gt;You’re not locked into one pattern:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;record struct — value-type records&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;readonly record struct — fully immutable&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Abstract and sealed record inheritance supported&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt; Reference:&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history#c-version-10&quot;&gt;What's New in C# 10 – Record Structs&lt;/a&gt;&lt;/p&gt;
&lt;p&gt; Records and the Value Object Pattern&lt;br&gt;
In Domain-Driven Design (DDD), Value Objects are small objects that:&lt;/p&gt;
&lt;p&gt;Represent a concept (e.g., Money, Email)&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Are immutable&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Have no identity&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Compare by value&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;✅ Records Are Ideal for Value Objects&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public record Email(string Address)
{
    public Email
    {
        if (!Address.Contains(&quot;@&quot;))
            throw new ArgumentException(&quot;Invalid email&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You get a clean, reusable object with built-in validation and equality , no fuss.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public record Money(decimal Amount, string Currency);

public record Product
{
    public Guid Id { get; init; }
    public string Name { get; init; }
    public Money Price { get; init; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt; Reference:&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://martinfowler.com/bliki/ValueObject.html&quot;&gt;Martin Fowler – Value Object&lt;/a&gt;&lt;/p&gt;
&lt;p&gt; When Not to Use Records&lt;/p&gt;
&lt;p&gt;Avoid records if:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;You need full mutable entities (e.g., for EF Core)&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;You rely on reference identity&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Your inheritance hierarchy is too complex&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt; Real-World Use Cases&lt;/p&gt;
&lt;p&gt;✅ DTOs for APIs&lt;/p&gt;
&lt;p&gt;✅ Immutable configs&lt;/p&gt;
&lt;p&gt;✅ Logging and audit trails&lt;/p&gt;
&lt;p&gt;✅ Domain Value Objects&lt;/p&gt;
&lt;p&gt;✅ State models in Blazor, Redux, Fluxor&lt;/p&gt;
&lt;p&gt;✅ Event-driven architecture&lt;/p&gt;
&lt;p&gt; Final Thoughts&lt;br&gt;
C# records are more than just syntactic sugar — they promote a mindset of immutability, clarity, and value-based design.&lt;/p&gt;
&lt;p&gt;They:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Reduce bugs&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Simplify data models&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Improve thread safety&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Save a lot of time&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Whether you're building APIs, desktop apps, or microservices, records make your C# experience cleaner and smarter.&lt;/p&gt;
&lt;p&gt;Once you go record, you'll never want to class again. &lt;/p&gt;
&lt;p&gt; References:&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record&quot;&gt;Microsoft Docs – Records&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init&quot;&gt;Init-only Setters in C# 9&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.codeguru.com/csharp/c-sharp-immutability/&quot;&gt;Immutability&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching&quot;&gt;Pattern Matching&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#records&quot;&gt;Dev Blog – Welcome to C# 9&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://martinfowler.com/bliki/ValueObject.html&quot;&gt;Martin Fowler – Value Objects&lt;/a&gt;&lt;/p&gt;
</description>
<category>C#</category>
<guid isPermaLink="true">https://coderlegion.com/2949/why-records-in-c-are-great-and-so-nice-to-work-with</guid>
<pubDate>Sat, 10 May 2025 20:37:38 +0000</pubDate>
</item>
<item>
<title>How to Bind a MudSelect from an External Source in Blazor Using MudBlazor</title>
<link>https://coderlegion.com/1832/how-to-bind-a-mudselect-from-an-external-source-in-blazor-using-mudblazor</link>
<description>&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://dotnet.microsoft.com/en-us/apps/aspnet/web-apps/blazor&quot;&gt;Blazor&lt;/a&gt; is a modern framework from Microsoft that allows you to build interactive web applications using C# and .NET, both on the server and the client, without needing JavaScript. It brings the full power of .NET to the browser via WebAssembly or server-side rendering.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://mudblazor.com/&quot;&gt;MudBlazor&lt;/a&gt; is a popular UI component library built specifically for Blazor. It offers clean, responsive components following Google's Material Design system, making it incredibly easy to create modern, beautiful, and interactive web UIs entirely in C#.&lt;/p&gt;
&lt;p&gt; &lt;strong&gt;Use Case&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Let’s say you need to:&lt;/p&gt;
&lt;p&gt;Display a multi-select dropdown&lt;/p&gt;
&lt;p&gt;Load the options from an external service&lt;/p&gt;
&lt;p&gt;Sync selected values with the parent component&lt;/p&gt;
&lt;p&gt;Reuse this logic throughout your application&lt;/p&gt;
&lt;p&gt;We'll walk through a real-world pattern using MudSelect, bound to a list of brands (dtoBrands) provided by a service.&lt;/p&gt;
&lt;p&gt; &lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A Blazor project with MudBlazor installed&lt;/p&gt;
&lt;p&gt;A service that returns the brand data&lt;br&gt;
A DTO like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class BrandDto
{
    public string Text { get; set; }
    public string Value { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt; Sample Service Interface&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public interface IBrandService
{
    Task&amp;lt;IEnumerable&amp;lt;BrandDto&amp;gt;&amp;gt; GetBrandsAsync();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt; The MudSelect Markup&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;MudSelect T=&quot;BrandDto&quot;
           Label=&quot;@Label&quot;
           MultiSelection=&quot;true&quot;
           Clearable=&quot;true&quot;
           @bind-SelectedValues=&quot;InternalSelectedValues&quot;
           ToStringFunc=&quot;item =&amp;gt; item.Text&quot;&amp;gt;
    @if (dtoBrands.Any())
    {
        @foreach (var item in dtoBrands)
        {
            &amp;lt;MudSelectItem T=&quot;BrandDto&quot; Value=&quot;item&quot;&amp;gt;
                @item.Text
            &amp;lt;/MudSelectItem&amp;gt;
        }
    }
&amp;lt;/MudSelect&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;⚙️ Component Logic&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;@inject IBrandService BrandService

@code {
    [Parameter]
    public string Label { get; set; } = &quot;Select Brands&quot;;

    [Parameter]
    public IEnumerable&amp;lt;BrandDto&amp;gt; SelectedValues { get; set; } = new HashSet&amp;lt;BrandDto&amp;gt;();

    [Parameter]
    public EventCallback&amp;lt;IEnumerable&amp;lt;BrandDto&amp;gt;&amp;gt; SelectedValuesChanged { get; set; }

    protected IEnumerable&amp;lt;BrandDto&amp;gt; dtoBrands = new List&amp;lt;BrandDto&amp;gt;();

    private IEnumerable&amp;lt;BrandDto&amp;gt; _internalSelectedValues = new HashSet&amp;lt;BrandDto&amp;gt;();

    private IEnumerable&amp;lt;BrandDto&amp;gt; InternalSelectedValues
    {
        get =&amp;gt; _internalSelectedValues;
        set
        {
            if (_internalSelectedValues != value)
            {
                _internalSelectedValues = value;
                SelectedValuesChanged.InvokeAsync(_internalSelectedValues);
            }
        }
    }

    protected override async Task OnInitializedAsync()
    {
        dtoBrands = await BrandService.GetBrandsAsync();

        _internalSelectedValues = new HashSet&amp;lt;BrandDto&amp;gt;(
            dtoBrands.Where(x =&amp;gt; SelectedValues.Any(s =&amp;gt; s.Value == x.Value))
        );
    }

    public override async Task SetParametersAsync(ParameterView parameters)
    {
        await base.SetParametersAsync(parameters);

        _internalSelectedValues = new HashSet&amp;lt;BrandDto&amp;gt;(
            dtoBrands.Where(x =&amp;gt; SelectedValues.Any(s =&amp;gt; s.Value == x.Value))
        );
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt; How It Works&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=1170082142962582969&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;♻️ Example Usage&lt;/p&gt;
&lt;p&gt;Imagine turning this into a reusable component, like BrandSelector.razor. You’d use it like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;BrandSelector Label=&quot;Choose Brands&quot;
               SelectedValues=&quot;@selectedBrands&quot;
               SelectedValuesChanged=&quot;@OnSelectedBrandsChanged&quot; /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt; Why This Pattern Rocks&lt;/p&gt;
&lt;p&gt;By combining Blazor's powerful component model with MudBlazor's modern UI toolkit, you get:&lt;/p&gt;
&lt;p&gt;✅ Fully data-driven dropdowns&lt;/p&gt;
&lt;p&gt;✅ Type-safe C# components&lt;/p&gt;
&lt;p&gt;✅ No need for JavaScript&lt;/p&gt;
&lt;p&gt;✅ A consistent look and feel&lt;/p&gt;
&lt;p&gt;And all of it is maintainable and testable across large-scale apps.&lt;/p&gt;
&lt;p&gt;✅ Final Thoughts&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Blazor&lt;/strong&gt; and &lt;strong&gt;MudBlazor&lt;/strong&gt; are a dream combo for building modern web apps in C#. By binding a MudSelect to an external service, you're creating a highly flexible and reusable pattern that fits beautifully in a clean architecture.&lt;/p&gt;
&lt;p&gt; Useful Links&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/aspnet/core/blazor/?view=aspnetcore-9.0&quot;&gt;Blazor documentation&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://mudblazor.com/&quot;&gt;MudBlazor official site&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://mudblazor.com/api/mudselect#pages&quot;&gt;MudSelect documentation&lt;/a&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/1832/how-to-bind-a-mudselect-from-an-external-source-in-blazor-using-mudblazor</guid>
<pubDate>Thu, 10 Apr 2025 09:15:42 +0000</pubDate>
</item>
<item>
<title>EF Core Global Query Filters: A Complete Guide</title>
<link>https://coderlegion.com/1323/ef-core-global-query-filters-a-complete-guide</link>
<description>&lt;p&gt;Entity Framework Core (EF Core) Global Query Filters allow you to apply filters to queries at the model level so that they automatically apply to all queries involving a specific entity. &lt;/p&gt;
&lt;p&gt;This is particularly useful for scenarios like soft deletes, multi-tenancy, and user-based data filtering.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;What is a Global Query Filter?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A global filter is a LINQ predicate that applies automatically to all queries on a specific entity type. &lt;/p&gt;
&lt;p&gt;This means that any time you query the database, EF Core applies the filter implicitly, reducing the need for adding Where clauses manually.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Use Cases&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Soft Deletes – Automatically filter out entities where IsDeleted =&lt;br&gt;
true.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Multi-Tenancy – Ensure that a tenant only accesses their own data.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;User-Based Filtering – Restrict users to see only their own records.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;How to Define a Global Query Filter&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Global filters are defined in the OnModelCreating method inside the &lt;strong&gt;DbContext&lt;/strong&gt; class using the HasQueryFilter method.&lt;/p&gt;
&lt;p&gt;Example : Soft Delete Implementation  ..&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class BaseEntity
{
    public bool IsDeleted { get; set; }
}

public class Product : BaseEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class AppDbContext : DbContext
{
    public DbSet&amp;lt;Product&amp;gt; Products { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&amp;lt;Product&amp;gt;()
            .HasQueryFilter(p =&amp;gt; !p.IsDeleted);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt; Now, every query on Products automatically filters out records where &lt;strong&gt;IsDeleted&lt;/strong&gt; = true.&lt;/p&gt;
&lt;p&gt;Querying Products&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var products = context.Products.ToList(); // Implicitly applies &quot;WHERE IsDeleted = 0&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Bypassing the Global Filter&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;You can explicitly disable the filter using .IgnoreQueryFilters().&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var allProducts = context.Products.IgnoreQueryFilters().ToList();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Applying Filters Dynamically (Multi-Tenancy Example)&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class AppDbContext : DbContext
{
    private readonly int _tenantId;

    public AppDbContext(DbContextOptions&amp;lt;AppDbContext&amp;gt; options, ITenantProvider tenantProvider)
        : base(options)
    {
        _tenantId = tenantProvider.GetTenantId();
    }

    public DbSet&amp;lt;Order&amp;gt; Orders { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&amp;lt;Order&amp;gt;()
            .HasQueryFilter(o =&amp;gt; o.TenantId == _tenantId);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt; &lt;strong&gt;Now, EF Core automatically filters records based on _tenantId.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Limitations and Considerations&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Filters do not apply to raw SQL queries (FromSqlRaw).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Navigation properties respect global filters (e.g., if Order has OrderDetails, the filter applies to them too).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Ensure filters do not cause unexpected performance issues on large datasets.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;You can define multiple query filters per entity.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Combining Multiple Filters&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;modelBuilder.Entity&amp;lt;Product&amp;gt;()
    .HasQueryFilter(p =&amp;gt; !p.IsDeleted)
    .HasQueryFilter(p =&amp;gt; p.Status == &quot;Active&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This results in:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;SELECT * FROM Products WHERE IsDeleted = 0 AND Status = 'Active'
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Disabling All Global Filters&lt;/p&gt;
&lt;p&gt;You can disable all filters for a specific context query using:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var allOrders = context.Orders.IgnoreQueryFilters().ToList();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Conclusion&lt;br&gt;
EF Core’s Global Query Filters help enforce consistent rules across queries without adding redundant Where clauses. They are a powerful feature for soft deletes, multi-tenancy, and user-based access control. However, they should be used carefully, considering potential performance impacts.&lt;/p&gt;
&lt;p&gt;Source Code&lt;/p&gt;
&lt;p&gt;You can find the complete source code for this tutorial at:&lt;br&gt;
 &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/stevsharp/EfCoreAndGlobalFilter&quot;&gt;GitHub Repository&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Here are some useful references to learn more about EF Core Global Query Filters and Soft Delete:&lt;/p&gt;
&lt;p&gt; Official EF Core Documentation&lt;br&gt;
Global Query Filters&lt;br&gt;
 &lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/ef/core/querying/filters&quot;&gt;https://learn.microsoft.com/en-us/ef/core/querying/filters&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Entity Framework Core SQLite Provider&lt;br&gt;
 &lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/ef/core/providers/sqlite/&quot;&gt;https://learn.microsoft.com/en-us/ef/core/providers/sqlite/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Managing Data with EF Core&lt;br&gt;
 &lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/ef/core/&quot;&gt;https://learn.microsoft.com/en-us/ef/core/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Community Articles &amp;amp; Tutorials&lt;br&gt;
EF Core: Global Query Filters for Soft Deletes&lt;br&gt;
 &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.thinktecture.com/en/entity-framework-core/global-query-filters/&quot;&gt;https://www.thinktecture.com/en/entity-framework-core/global-query-filters/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Implementing Soft Delete in EF Core&lt;br&gt;
 &lt;a rel=&quot;nofollow&quot; href=&quot;https://medium.com/swlh/soft-delete-in-entity-framework-core-6c6b7a9784c7&quot;&gt;https://medium.com/swlh/soft-delete-in-entity-framework-core-6c6b7a9784c7&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Using SQLite with EF Core in Console Applications&lt;br&gt;
 &lt;a rel=&quot;nofollow&quot; href=&quot;https://code-maze.com/using-sqlite-with-entity-framework-core/&quot;&gt;https://code-maze.com/using-sqlite-with-entity-framework-core/&lt;/a&gt;&lt;/p&gt;
</description>
<category>C#</category>
<guid isPermaLink="true">https://coderlegion.com/1323/ef-core-global-query-filters-a-complete-guide</guid>
<pubDate>Sun, 02 Mar 2025 09:42:51 +0000</pubDate>
</item>
</channel>
</rss>