Moonglade

Modern Markdown blogging with AI-powered localization and search.

Tag: .NET


How to Enjoyably Develop .NET with AnduinOS

This article aims to provide .NET developers with a guide for setting up a development environment in VSCode on AnduinOS or any Linux system that closely mimics the Visual Studio experience. It begins by noting that, due to the lack of a free Visual Studio and the absence of a Rider Community Edition, VSCode emerges as an ideal alternative. The core content recommends the C# extension and its key settings, such as enabling OmniSharp decompilation support, EditorConfig, and the Roslyn analyzer, to enhance basic functionality. For advanced needs, it introduces the C# Dev Kit and its intelligent completion components, while cautioning about its commercial licensing restrictions and account login requirements. Additionally, it recommends Roslynator as a lightweight alternative for code analysis and refactoring, along with practical plugins for automatically generating XML documentation comments and completing namespaces. The article also briefly discusses the pros and cons of GitHub Copilot. The author emphasizes that these configurations can significantly improve development efficiency and invites readers to share further optimization suggestions, aiming to help developers achieve a smoother C# development experience on Linux platforms.

Views 312
.NET AnduinOS C# VSCode development-environment dotnet github-copilot vscode-plugins

You might be writing .NET code that has memory leaks!

This article systematically reviews six common memory leak scenarios in .NET development and their corresponding mitigation strategies, aiming to help developers avoid production incidents. It first explains the concepts of managed and unmanaged memory, pointing out that failing to properly release resources prevents the GC from reclaiming them. The specific scenarios include: anonymous methods capturing class members forming strong references, with a recommendation to use local variables instead; event subscriptions preventing subscriber release, requiring timely unsubscription or the use of weak references; static variables, especially collection types, which can grow indefinitely and are not collected by the GC; using mutable collections as caches in long-lived objects, which can easily lead to memory exhaustion, with a recommendation to switch to `IMemoryCache` with expiration mechanisms; failure to call `Dispose` leading to unmanaged resource leaks, where using `using` statements is preferred over relying on finalizers due to their higher performance overhead; and direct memory operations such as `unsafe`, which require extra caution. The article emphasizes that even experienced developers can make mistakes, and that mastering these patterns and maintaining disciplined coding habits are crucial to effectively improving application stability and avoiding out-of-memory exceptions.

Views 178
.NET Circular Dependencies Closure Issues Memory Caching Issues Memory Leaks Unmanaged Resources

5-Minute Introduction to .NET Unit Testing ★

This article is an introductory tutorial on C# unit testing. Using BookService as an example, it provides a detailed demonstration of the complete process of writing tests with xUnit, NSubstitute, and FluentAssertions. The article first introduces the basic construction of test classes, including creating mock objects with NSubstitute, initializing the system under test, and preparing test data. It then focuses on writing test methods, distinguishing between the [Fact] and [Theory] attributes: [Fact] is used for testing a single scenario and follows the standard Arrange (setup), Act (execution), and Assert (verification) structure; [Theory] combined with [InlineData] supports multiple sets of input parameters, making it particularly suitable for verifying exception throwing or boundary conditions. The tutorial also demonstrates how to use Arg.Any<T> to handle arbitrary parameters, and introduces methods for running tests and viewing results via the dotnet test command or an IDE. The article emphasizes improving code readability through normalized test method naming conventions (such as Method_Scenario_ExpectedResult), and points out that unit testing can effectively prevent missed parameter validation, making it an important practice for ensuring code quality.

Views 278
.NET Test nsubstitute tdd unit testing xunit

Using Moq Events to Discuss the Importance of Unit Testing

The prominent .NET unit testing library Moq sparked intense community controversy after it was discovered that the library scans local Git configurations during the build process and sends users' email addresses to check their sponsorship status. This led some developers to condemn the author and resulted in the emergence of alternative solutions such as CleanMoq. Using this incident as a starting point, the article delves into the core value of unit testing, pointing out that it can significantly enhance code quality, maintainability, and refactoring efficiency. Conversely, the absence of unit testing can lead to a vicious cycle of fragile code, increased project risks, and reduced development efficiency. Although this incident did not trigger widespread discussion domestically, the author reflects on the fact that small and medium-sized companies in the region generally lack a habit of writing unit tests. This is attributed to cost considerations and time pressures, which ultimately result in declining software quality. The article calls on local developers and enterprises to place greater importance on unit testing, breaking the dilemma where a lack of tests prevents refactoring and code rot slows down development. The author also plans to share introductory tutorials on unit testing in the future.

Views 206
.NET Code Quality Software Development Software Development Methodology Test unit testing

A comic strip explaining the principles of .NET garbage collection (GC)

Set against the backdrop of the 2023 Lunar New Year's Eve, this article explores the prevalent "assembly-line" development predicament faced by .NET developers in China. It points out that many developers focus solely on business-level CRUD operations while neglecting underlying technical principles, which hinders their long-term career growth. The author advocates breaking through this bottleneck via performance optimization, emphasizing that reducing Garbage Collection (GC) pressure is the core entry point for .NET performance tuning. The article translates and introduces a classic .NET GC principle comic created by Redgate, aiming to provide foundational technical education for developers. Additionally, it offers an in-depth analysis of the technical challenges involved in Large Object Heap (LOH) compaction. It mentions a temporary workaround involving setting `GCSettings.LargeObjectHeapCompactionMode` to `CompactOnce`, but notes that this method has time-sensitivity limitations and requires manual intervention, effectively reverting to the complexity of manual memory management. The article advises readers to deepen their understanding of .NET's memory management mechanisms by adopting a multi-language programming perspective.

Views 187
.NET comic translation dotnet garbage collection large object heap performance optimization

How is .NET compiled? How do you read the intermediate language?

This article provides an in-depth analysis of the compilation mechanism of C# on the dotnet platform, highlighting its hybrid approach that combines static compilation with Just-In-Time (JIT) compilation. First, the compiler statically compiles C# source code into Common Intermediate Language (CIL/IL) and encapsulates it in PE or PE+ executable files. This stage involves NuGet package restoration and building in either Debug or Release mode; the Release mode offers better performance and security due to the removal of debugging information. Subsequently, at runtime, the Common Language Runtime (CLR) takes over the process, using the JIT compiler to dynamically convert IL into native machine code specific to the current platform, thereby achieving a balance between cross-platform compatibility and execution efficiency. The article also uses the Pythagorean theorem as an example to detail the structure of the IL instruction set, including method declarations, stack operations, local variable initialization, and specific execution logic, helping readers understand the actual low-level mapping of the code. Mastering this process not only helps eliminate doubts about the compilation black box but also enables more precise judgments when optimizing performance or comparing the overhead of different implementations by reading IL code.

Views 188
.NET .NET Framework C# Compilation Intermediate Language JIT Compiler performance optimization

[Translation] .NET SDK Will Have Built-in Container Support, No Longer Requiring a Dockerfile

This article introduces the new container image build feature in the .NET 7 SDK, designed to resolve the issue of missing configuration files caused by inconsistencies between the traditional Dockerfile build context and the dotnet build process. By leveraging the new TAR API introduced in .NET 7, this feature generates container images directly via MSBuild properties, eliminating the need to write complex Dockerfiles. Its core advantage lies in seamless integration with existing build logic. It automatically selects a Debian-based base image by default and supports customizing the image name, version, and underlying system (such as Alpine) through properties like ContainerBaseImage. Although it currently does not support executing RUN commands, pushing to remote repositories, or creating Windows images, custom base images can be used to meet native dependency installation needs, and these features will be progressively enhanced in future versions. The article recommends trying this feature in local development or CI pipelines to simplify the containerization workflow. While Dockerfiles remain more flexible, the SDK-integrated approach offers a more convenient automated experience in specific scenarios.

Views 172
.NET .NET SDK Container Builds Docker GitHub Actions Linux x64

Still memorizing the concept of dependency injection? Why not write your own dependency injection framework?

This article introduces the core implementation and testing process of KDI, a custom Dependency Injection (DI) framework built with C#. KServiceProvider registers services by iterating through KServiceCollection. For the Transient lifetime, it uses Func delegates to ensure a new instance is created every time a service is requested. For the Singleton lifetime, it leverages Lazy objects to implement lazy loading while guaranteeing global uniqueness. Through Guid service tests, the correctness of both lifetimes was verified: Singleton returns the same instance on multiple requests, whereas Transient returns a different instance each time. The article concludes with a profound critique of exam-oriented programming learning mindsets, pointing out that Scoped and Singleton behaviors have fundamental differences in console applications. Blindly applying interview techniques can lead to misunderstandings of underlying principles. The author emphasizes the importance of deeply understanding Dependency Injection mechanisms rather than rote memorization, and reminds readers to be aware of the security risks associated with the Service Locator pattern in production environments, as well as the room for improvement in the framework. Developers are encouraged to abandon rigid thinking and cultivate genuine creativity.

Views 130
.NET Dependency Injection DependencyInjection Design Patterns Service Lifecycles Software Engineering

Simplifying DDD Value Object Comparison with EF Core Dynamic Expression Trees

This article explores technical solutions for implementing semantic equality queries with value objects in EF Core. It first points out that traditional field-by-field query code is verbose and lacks semantic clarity, while directly comparing value objects for equality results in a compilation exception. To address this, the article proposes and implements a generic `ValueObjectEqualHelper` static class, whose core is the `CheckEqual` method. This method dynamically builds expression trees, iterates through the value object's properties, automatically skips null values to avoid generating redundant `IS NULL` conditions, and correctly constructs binary expression trees for equality comparisons based on property types (primitive or reference types), finally connecting all conditions with `AndAlso` logic. This approach preserves the intuitive semantics of `p => p.Address == new Address(...)` while being correctly translated into SQL by EF Core, solving the pain point of being unable to directly compare value objects for equality in database queries and providing a generic and elegant implementation path.

Views 168
.NET C# Dynamic Condition Generation EF Core Entity Framework Core expression trees

Dynamically Building Expression Trees in EF Core to Set Soft Delete Query Filters for All Entities

This article introduces two QueryFilter configuration approaches for implementing soft delete in Entity Framework Core. First, it demonstrates the conventional method of manually adding `builder.HasQueryFilter(x => !x.SoftDelete)` in each entity configuration class. While simple and direct, this approach incurs high maintenance costs when dealing with a large number of entities. Subsequently, it proposes a superior dynamic expression tree construction scheme. By iterating through all entity types in the model, this approach automatically detects the presence of a `bool` type `SoftDelete` property and uses the `Expression` class to dynamically generate the `x => !x.SoftDelete` Lambda expression to uniformly set the query filter. This method eliminates code duplication and achieves global automation of soft delete filtering. The article also demonstrates how to use the `IgnoreQueryFilters()` method to ignore the filter when necessary to query deleted data, and provides various code implementations ranging from detailed construction to simplified syntax. Finally, it emphasizes the flexibility and vitality of C# syntax in constructing expression trees.

Views 136
.NET Dynamic Expression Trees EF Core Entity Framework Core Soft Delete lambda expressions