.Net Recipe Part-1

Shubham Dhumal
6 min readJul 8, 2024

--

.Net Core is renamed to .Net 5 we currently using .Net 8

The latest version of .NET Core is .NET 8, which is a Long-Term Support (LTS) release. The most recent update, .NET 8.0.6, was released in June 2024. This version includes improvements to performance, garbage collection, and core libraries. Additionally, .NET 8 introduces new features in ASP.NET Core, Entity Framework Core.

To help you learn .NET Core through a practical approach using CRUD operations, here’s an adjusted plan that leverages your familiarity with C# Web API:

Week 1: Setup and Basics

  1. Environment Setup
  • Install the latest .NET SDK.
  • Set up an IDE like Visual Studio or VS Code.

2. Basic Concepts

  • Review the fundamentals of .NET Core and .NET 8.
  • Understand project structure and basic commands (dotnet new, dotnet run, etc.).

3. Hello World API

  • Create a simple Web API project.
  • Understand the MVC pattern and how it applies to .NET Core.

Week 2: Building the API

  1. Models, Controllers, and Actions
  • Define models for your application (e.g., Product, Customer).
  • Create controllers with basic CRUD actions (Create, Read, Update, Delete).

2. Entity Framework Core

  • Set up a database using EF Core.
  • Implement CRUD operations with EF Core.

Week 3: Advanced Features

  1. Data Validation and Error Handling
  • Implement data validation using Data Annotations.
  • Add global error handling and custom error responses.

2. Authentication and Authorization

  • Add authentication to your API using JWT.
  • Implement role-based authorization.

Week 4: Testing and Deployment

  1. Unit Testing
  • Write unit tests for your controllers and services using xUnit.
  • Mock dependencies using Moq.

2. Integration and Deployment

  • Test the full API using tools like Postman.
  • Deploy your API to a cloud service like Azure.

Week 5: Continuous Learning

  1. Explore Advanced Topics
  • Look into advanced features in .NET 8 like minimal APIs, Blazor integration, and performance tuning.

2. Build a Complete Project

  • Start a more complex project that integrates all the concepts you’ve learned.
  • Regularly update your knowledge with the latest features and best practices.

For comprehensive details on what’s new in .NET 8, refer to the official Microsoft documentation.

launchSettings.json Overview

  • Purpose: Contains configuration settings for launching the application.
  • Settings Included:
  • Environment variables
  • Application URLs
  • Usage: Utilized by .NET Core Framework when running the application from Visual Studio or .NET Core CLI.
  • Note: This file is used only on the local development machine.

appsettings.json Overview

  • Purpose: Acts as the application configuration file in ASP.NET Core Web Applications.
  • Equivalent: Similar to web.config or app.config in traditional .NET Framework applications.
  • Contents: Stores various configuration settings, including:
  • Database connection strings
  • API keys
  • Logging settings
  • Usage: Utilized by the application to retrieve configuration settings during runtime.

In a .NET 8 project, the Program.cs file serves as the entry point of the application. This is where the execution begins for a .NET application. Starting with .NET 6 and continuing with .NET 8, the default template for ASP.NET Core projects adopts a minimal hosting model with a simplified structure. The key points of the Program.cs file are:

  • Entry Point: The application execution begins in this file.
  • Simplified Structure: Uses a minimal hosting model for a cleaner setup.
  • Default Template: The template includes essential components to set up and run the application.
  • Configuration: Contains configuration and setup code for the application.
  • Hosting: Sets up the web host and specifies the startup configuration.

Example code structure:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();
app.Run();record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

WebApplicationBuilder

WebApplicationBuilder is a tool in ASP.NET Core that helps you set up your web application. It configures services, middleware, settings, and endpoints in an organized way.

WebApplication

Once you’ve set up everything with WebApplicationBuilder, you use .Build() to create a WebApplication. This final product runs your web app and handles incoming requests.

AddEndpointsApiExplorer

The AddEndpointsApiExplorer() method is used to enable API Explorer services required for generating the OpenAPI specification. This method adds services necessary for discovering endpoint metadata. This metadata is essential for tools like Swagger to generate accurate and useful documentation for your Web API.

AddSwaggerGen

The AddSwaggerGen() method adds Swagger generator services to the project. These services are responsible for generating Swagger documents, which describe the structure and capabilities of your Web API. This method allows for customization of the Swagger documentation, such as setting the title and version and even adding custom descriptions and schemas.

What is DTO’s?

  • Definition: DTO stands for Data Transfer Object, a design pattern used to transfer data.
  • Purpose: Primarily used to pass data in a structure convenient for consumers.
  • Usage in API Development:
  • Send responses
  • Receive requests
  • Decoupling: Helps decouple the internal database/entity model from the external interface.
  • Changes to the database model don’t necessarily affect the API contracts.
  • Characteristics: Typically a simple object with no business logic.
namespace SaaSKit.Contracts.Api;
public record class Users (int id, string firstName, string lastName, string email);

With….

  • .WithName("GetBooks"): Assigns a name to the endpoint for clarity.
  • .WithOpenApi(...): Adds descriptive information for the Swagger UI, enhancing API documentation.

Architecture

The Domain-Driven Design (DDD) architecture typically involves organizing a software system into distinct layers or modules, each with its own responsibilities and dependencies. Here’s an explanation of the key layers in DDD: API, Application, Domain, and Infrastructure.

  1. Domain Layer:
  • Responsibility: This layer represents the core business logic and rules of the application. It encapsulates entities, value objects, aggregates, domain services, and repositories.
  • Components:
  • Entities: Objects that have a distinct identity and lifecycle within the domain. They encapsulate behavior and data related to a specific business concept.
  • Value Objects: Immutable objects without a distinct identity. They are used to describe attributes or characteristics of entities.
  • Aggregates: Consist of entities and value objects that are treated as a single unit of consistency. They enforce business rules and transaction boundaries.
  • Domain Services: Encapsulate domain-specific operations that don’t naturally belong to any entity or value object.
  • Repositories: Provide an abstraction for storing and retrieving aggregates.

2. Application Layer:

  • Responsibility: Coordinates the application’s behavior and interacts with external clients (such as APIs or UIs). It orchestrates domain objects to fulfill use cases or application workflows.
  • Components:
  • Application Services: Define the application’s use cases. They coordinate the domain layer and interact with infrastructure services.
  • DTOs (Data Transfer Objects): Objects used to exchange data between layers or with external systems. They encapsulate data that is passed to or from the application layer.

3. API (Presentation) Layer:

  • Responsibility: Exposes the application’s functionality to external systems or users. It handles requests, validates input, and formats responses.
  • Components:
  • Controllers or Handlers: Receive incoming requests, invoke application services or domain objects, and return responses.
  • Models: Represent data structures used within the API layer.

4. Infrastructure Layer:

  • Responsibility: Provides supporting services and utilities required by the application. This includes data access, external integrations, logging, and configuration management.
  • Components:
  • Persistence: Implements repositories and data access mechanisms (e.g., using ORM frameworks like Entity Framework or raw SQL).
  • External Services: Integration with external APIs or systems (e.g., payment gateways, email services).
  • Logging and Monitoring: Captures and analyzes application logs, performance metrics, and error reporting.
  • Configuration Management: Handles application settings and environment-specific configurations.

Interaction between Layers:

  • The API layer receives requests from external clients and invokes corresponding controllers or handlers.
  • Controllers in turn invoke application services in the application layer to perform use cases.
  • Application services coordinate with domain entities and services in the domain layer to enforce business rules and perform operations.
  • Domain entities interact with repositories in the infrastructure layer to persist data.
  • Infrastructure services (like logging or external services) support the entire application stack.

Conclusion

The document provides a comprehensive guide to learning .NET 8, covering setup, building APIs, advanced features, testing, deployment, and continuous learning. It includes detailed explanations of key components like launchSettings.json, appsettings.json, Program.cs, WebApplicationBuilder, and WebApplication. It also explains DTOs and their usage in API development and outlines the Domain-Driven Design (DDD) architecture, detailing the responsibilities and components of the Domain, Application, API, and Infrastructure layers.

--

--