A practical guide to mastering overlooked .NET fundamentals
🧭 Introduction
Even experienced .NET developers occasionally run into subtle gaps in understanding—especially around service lifecycles, middleware behavior, runtime terminology, and web fundamentals like cookies. This post explores these areas with practical examples and explanations, helping you build more robust, secure, and maintainable applications.
🔁 Dependency Injection Lifecycles in .NET
Dependency Injection (DI) is central to ASP.NET Core architecture. Understanding service lifecycles helps you avoid performance issues and bugs related to object reuse and state management.
Lifecycle | Description | Use Case |
---|---|---|
Transient | New instance per request. | Lightweight, stateless services. |
Scoped | One instance per request. | Services maintaining request-level state. |
Singleton | One instance for app lifetime. | Shared, stateless, expensive-to-create services. |
🧠 Key Considerations
- Singleton services must be thread-safe.
- Scoped services are ideal for per-request data (e.g., EF Core
DbContext
). - Transient services can be wasteful if they involve heavy initialization.
🧱 ASP.NET Core Middleware Pipelines
Middleware components form the backbone of request processing in ASP.NET Core. They’re executed in the order registered and can modify or short-circuit the request pipeline.
🔧 Example Configuration
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
🧠 Key Concepts
- Middleware can inspect, modify, or terminate requests.
- Order matters:
UseRouting
must precedeUseAuthorization
, for example. - Custom middleware can encapsulate cross-cutting concerns like logging or error handling.
🛠 Custom Middleware Example
public class LoggingMiddleware
{
private readonly RequestDelegate _next;
public LoggingMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context)
{
Console.WriteLine($"Request: {context.Request.Path}");
await _next(context);
Console.WriteLine($"Response: {context.Response.StatusCode}");
}
}
Register with: app.UseMiddleware<LoggingMiddleware>();
⚙️ What Does "Managed" Mean in C#?
Managed code runs under the Common Language Runtime (CLR), which provides services like memory management, type safety, and exception handling.
📌 Characteristics
- Garbage Collection: Automatic memory cleanup.
- Type Safety: Prevents unsafe operations.
- Security: Enforced via runtime checks and sandboxing.
🧠 Managed vs. Unmanaged Code
Feature | Managed Code | Unmanaged Code |
---|---|---|
Memory Management | Automatic via CLR | Manual (malloc , free ) |
Security | Type-safe, sandboxed | Direct memory access |
Language Examples | C#, VB.NET | C, C++ |
Interop | P/Invoke, COM Interop | Requires wrappers |
Understanding this distinction is key when integrating with native libraries or optimizing performance-critical components.
🍪 Understanding Browser Cookies
Cookies are essential for session management, personalization, and tracking. ASP.NET Core provides a straightforward API for working with them.
🧠 Cookie Types
- Session Cookies: Deleted when browser closes.
- Persistent Cookies: Stored until expiration or manual deletion.
🛠 Setting Cookies in ASP.NET Core
Response.Cookies.Append("UserName", "Alice", new CookieOptions
{
Expires = DateTimeOffset.UtcNow.AddDays(1),
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Strict
});
🔐 Security Best Practices
- Use
HttpOnly
to prevent JavaScript access. - Use
Secure
to enforce HTTPS. - Use
SameSite=Strict
to mitigate CSRF. - Avoid storing sensitive data directly in cookies.
✅ Wrapping Up
These concepts—DI lifecycles, middleware pipelines, managed code, and cookies—are foundational to building modern .NET applications. By understanding their nuances, you’ll write cleaner, safer, and more efficient code. Whether you're refining your architecture or mentoring others, these insights will serve you well.
Top comments (0)