Meet The Author

I'm Ethan Jackson, An 25 years old blogger Currently living in London, United Kingdom. I'm a Skilled Blogger, Part Time web Developer And Creating new things as a web Designer.

author

An Introduction to Hangfire Integration in.NET 8

Leave a Comment

An open-source library called Hangfire is used in.NET applications to process jobs in the background. It enables you to carry out lengthy operations, such processing photos, sending emails, or any other work, asynchronously without interfering with the main request thread. Hangfire manages job persistence, retries, and scheduling to maintain the responsiveness of your application while guaranteeing the reliable execution of crucial background operations. 

Hangfire supports several types of jobs.

  • Fire-and-Forget Jobs: Executed only once immediately after creation.
  • Delayed Jobs: Scheduled to run after a specified delay.
  • Recurring Jobs: Run according to a defined schedule (e.g., every day at a particular time).
  • Continuation Jobs: Triggered when their parent job completes.

Prerequisites

Before you begin, ensure you have,

  • .NET 8 SDK installed.
  • A code editor (Visual Studio or VS Code).
  • SQL Server or LocalDB for job storage.
  • Basic knowledge of C# and ASP.NET Core.
Setting Up the Sample Project

1. Create a New Minimal API Project

Open your terminal.

dotnet new web -n HangfireSample

2. Add Hangfire NuGet Packages

Navigate to your project folder and run.

cd HangfireSample
dotnet add package Hangfire.AspNetCore
dotnet add package Hangfire.SqlServer
dotnet add Microsoft.Data.SqlClient

3. Configure the Database

Update appsettings.json with your connection string. For example, using LocalDB.

{
  "ConnectionStrings": {
    "HangfireConnection": "Server=Instance;Database=Your_DB;Integrated Security=True;TrustServerCertificate=true;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

Hangfire will automatically create the necessary tables.

Implementing Hangfire in .NET 8

Replace the contents of Program.cs with the following code.

using Hangfire;
using Hangfire.SqlServer;

var builder = WebApplication.CreateBuilder(args);

// Configure Hangfire to use SQL Server storage.
builder.Services.AddHangfire(config =>
{
    config.UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireConnection"));
});

// Start the Hangfire Server to process background jobs.
builder.Services.AddHangfireServer();

// (Optional) Add Swagger for API testing.
builder.Services.AddEndpointsApiExplorer();

var app = builder.Build();

// Use Swagger UI in development mode.
// Expose the Hangfire Dashboard at /hangfire (be sure to secure this in production).
app.UseHangfireDashboard();

// Root endpoint to test basic connectivity.
app.MapGet("/", () => "Hello World from .NET 8 and Hangfire!");

// Endpoint to enqueue a fire-and-forget job.
app.MapGet("/enqueue", (IBackgroundJobClient backgroundJobs) =>
{
    backgroundJobs.Enqueue(() => Console.WriteLine("Hangfire Fire-and-Forget Job executed!"));
    return Results.Ok("Background job has been enqueued.");
});
// New endpoint to schedule a delayed job (executes after 1 minute).
app.MapGet("/schedule", (IBackgroundJobClient backgroundJobs) =>
{
    backgroundJobs.Schedule(
        () => Console.WriteLine("Delayed Hangfire Job executed after 1 minute!"),
        TimeSpan.FromMinutes(1)
    );
    return Results.Ok("Delayed job scheduled to run after 1 minute.");
});

// Run the application.
app.Run();
How does This Work?

Hangfire Configuration

  • AddHangfire registers Hangfire with SQL Server storage using the provided connection string.
  • AddHangfireServer starts a background server to process the queued jobs.

Endpoints

  • Root ("/"): Returns a basic welcome message.
  • Enqueue ("/enqueue"): Uses BackgroundJob.Enqueue to immediately queue a fire-and-forget job.
  • Schedule ("/schedule"): Uses BackgroundJob.Schedule to queue a job that will execute after a 1-minute delay.
  • Hangfire Dashboard: Accessible at /hangfire, it provides real-time monitoring of job statuses (enqueued, processing, succeeded, or failed).
Visual Overview

Architecture Diagram

+-----------------------------+
|           Client           |
|   (Browser, Postman, etc.) |
+--------------+-------------+
               |
           HTTP Request
               |
               v
+-----------------------------+
|       .NET 8 Minimal API    |
| Endpoints:                 |
|   "/"         -> Hello World|
|   "/enqueue"  -> Enqueue    |
|   "/schedule" -> Delay      |
+--------------+-------------+
               |
     Enqueue / Schedule Command
               |
               v
+-----------------------------+
|   Hangfire Storage (SQL DB) |
+--------------+-------------+
               |
     Hangfire Server Polls
               |
               v
+-----------------------------+
| Hangfire Background Job     |
|        Processor            |
+-----------------------------+

Step-by-Step Flow

  • Client Interaction: A client calls /enqueues, or /schedules to add jobs.
  • Job Storage: Hangfire persists the job details in SQL Server.
  • Job Processing: The Hangfire server continuously polls the queue and executes ready jobs.
  • Dashboard Monitoring: The Hangfire Dashboard lets you view job states and monitor execution.

Key Terms Explained

  • Fire-and-Forget Job (Enqueue): Enqueued tasks that run as soon as they’re picked up. Ideal for operations that don't require an immediate response.
  • Delayed Job (Schedule): Tasks that start after a delay—useful for follow-up operations like sending reminders.
  • Background Job: Any task executed asynchronously outside the main HTTP request/response cycle.
  • Hangfire Server: A service that retrieves and executes background jobs from storage.
  • Hangfire Dashboard: A web-based UI for monitoring job statuses. For production, secure this dashboard with proper authentication.

Running and Testing

Start the Application

dotnet run

Test the Endpoints

  • Root: Navigate to http://localhost:5000/ to see "Hello World from .NET 8 and Hangfire!"
  • Enqueue: Visit http://localhost:5000/enqueue to dispatch a fire-and-forget job.
  • Schedule: Visit http://localhost:5000/schedule to schedule a job for execution after one minute.
  • Dashboard: Open http://localhost:5000/hangfire to monitor jobs in real time.

Output Samples

Conclusion
This tutorial covered both immediate (enqueue) and delayed (schedule) job processing, showing how to incorporate Hangfire into a.NET 8 Minimal API project. Long-running processes can be transferred to background jobs to maintain the scalability and responsiveness of your application.

Then, to enhance your background processing capabilities, think about investigating repeating jobs, job continuations, or including bespoke error handling.

Have fun with your coding!

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Fixed Window vs. Sliding Window Rate Limiting in .NET

Leave a Comment

1. Fixed Window Rate Limiting (in .NET)
What it is
The Fixed Window algorithm counts requests within a strict time window (like a box of time). When the window resets, the count resets too.

Example

  • Limit: 10 requests per minute.
  • Every minute (e.g., from 10:00:00 to 10:01:00), a new window opens.
  • If a client makes 10 requests at 10:00:05, they are allowed.
  • The next request (11th) before 10:01:00 will get blocked (HTTP 429 error).
  • At 10:01:00, the window resets and they can make requests again.
In .NET
options.AddSlidingWindowLimiter("sliding", opt =>
{
    opt.Window = TimeSpan.FromMinutes(1);   // 1-minute rolling window
    opt.PermitLimit = 10;                  // 10 requests allowed in the last minute
    opt.SegmentsPerWindow = 4;             // divide into 4 parts (15 seconds each)
    opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
    opt.QueueLimit = 2;
});

Pros

  • Very simple and fast to implement.
  • Good for low-traffic or non-critical APIs.

Cons

  • Allows “burst traffic” at the start of the window (all 10 requests may come instantly).
  • Not very "smooth" — users may hit the limit early and wait for the whole window.

2. Sliding Window Rate Limiting (in .NET)
What it is

The Sliding Window algorithm spreads the limit over a rolling period, not tied to a fixed block of time. It calculates how many requests were made in the last X minutes — no matter when the requests came.

Example

  • Limit: 10 requests per minute (rolling).
  • If 10 requests were made between 10:00:30 and 10:01:30, the limit applies based on that rolling window — not the wall clock.
  • This avoids a sudden "burst" problem and gives a smoother, fairer limit.

In .NET

options.AddSlidingWindowLimiter("sliding", opt =>
{
    opt.Window = TimeSpan.FromMinutes(1);   // 1-minute rolling window
    opt.PermitLimit = 10;                  // 10 requests allowed in the last minute
    opt.SegmentsPerWindow = 4;             // divide into 4 parts (15 seconds each)
    opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
    opt.QueueLimit = 2;
});

SegmentsPerWindow: The window is divided into smaller parts (helps tracking requests better).

Pros

  • Fairer and smoother — no sudden resets or spikes.
  • Prevents "burst" requests at the start of each minute.

Cons

  • Slightly more memory and CPU usage (to track rolling windows).
  • Complex to implement manually (but .NET does this for you).

When to Use Which?

Scenario Fixed Window Sliding Window
Simple internal APIs ✅ Good ❌ Overkill
Public APIs used by 1000s of users ❌ Not Recommended ✅ Better
Need smooth traffic flow (e.g., payment gateway) ❌ Bad for bursts ✅ Ideal
Want easy implementation without extra load ✅ Very Easy ❌ Slightly heavy

Interview Perspective

Q: What is the key difference between Fixed and Sliding window algorithms in API Rate Limiting?

  • Fixed Window resets the counter after each period (e.g., every minute).
  • Sliding Window checks requests across a rolling period, making limits smoother and avoiding bursts.
  • Sliding is better for high-traffic public APIs, while Fixed is good for simple, low-risk endpoints.
Real Example: Login API in .NET
Fixed Window
// Allow 5 login attempts every 60 seconds
options.AddFixedWindowLimiter("loginFixed", opt =>
{
    opt.Window = TimeSpan.FromSeconds(60);
    opt.PermitLimit = 5;
});
C#

Sliding Window

// Allow 5 login attempts in any rolling 60 seconds
options.AddSlidingWindowLimiter("loginSliding", opt =>
{
    opt.Window = TimeSpan.FromSeconds(60);
    opt.PermitLimit = 5;
    opt.SegmentsPerWindow = 6;  // 10 seconds each
});
Summary
Fixed Window Sliding Window
Simple, less resource-hungry Smooth, prevents burst requests
Allows initial bursts Spreads requests over time
Good for small/private APIs Best for public APIs, payment, login
Reset happens strictly by time Reset happens by rolling calculation

If you want, I can

  • Build a full sample .NET app demonstrating both types.
  • Help you prepare exact interview answers.
  • Show how to apply rate limiting per user/IP dynamically.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Using Redis in .NET Core Applications: An Overview

Leave a Comment

Modern applications frequently employ Redis, a quick in-memory key-value store, for caching, session storage, message brokering, and pub/sub communication. It is the preferred option for creating scalable systems since it is developer-friendly, lightweight, and performant.

This article will demonstrate how to use the StackExchange if you're working on a.NET Core project and wish to incorporate Redis into your application. Redis library to carry out fundamental Redis tasks. For Windows users, Redis can be run on a server that supports it without the need for Linux or containerization.

Why Redis?

Redis offers several benefits when integrated with a .NET Core application.

  1. Caching: Store frequently accessed data to improve response times and reduce database workloads.
  2. Session Management: Handle user sessions efficiently in distributed systems.
  3. Real-Time Events: Use Redis for pub/sub features to power real-time functionality like notifications or event-driven communication.
  4. High Performance: Operates in memory, offering low-latency data access.
  5. Scalable: With support for clustering and sharding, Redis is built for scalability.

Setting Up Redis

Using Redis

To connect your .NET Core app to Redis, you can run Redis either.

  • Command-Line Installation: Use tools like Docker to run Redis on Linux or Windows.
  • Pre-Configured Windows Alternative: If you’re on Windows, you can use a Redis-compatible server as a drop-in replacement for running Redis natively.

Note. For simplicity, this tutorial assumes Redis is running locally on localhost:6379.

Building a .NET Core Application with Redis

In this example, we’ll create a .NET Core console application that performs the following Redis operations.

  1. Connect to a Redis server.
  2. Perform basic key-value operations (set, get, delete).
  3. Demonstrate key expiration and validation.

Step 1. Create the .NET Core Project.

  1. Open a terminal and create a new project.

    dotnet new RedisIntegrationDemo

Step 2. Write the Code.

Here’s the full implementation in the Program.cs.

using System;
using StackExchange.Redis;
using System.Threading.Tasks;

namespace RedisIntegrationDemo
{
    class Program
    {
        // Connection string for Redis
        private const string RedisConnectionString = "localhost:6379";

        async static Task Main(string[] args)
        {
            Console.WriteLine("Connecting to Redis...");

            // Connect to Redis
            var redis = await ConnectionMultiplexer.ConnectAsync(RedisConnectionString);
            Console.WriteLine("Connected to Redis successfully.\n");

            // Access the Redis database
            IDatabase db = redis.GetDatabase();

            // Perform Redis operations
            Console.WriteLine("Performing Redis operations...");

            // 1. Set key-value pair
            string key = "SampleKey";
            string value = "Hello from Redis!";
            await db.StringSetAsync(key, value);
            Console.WriteLine($"Set: {key} => {value}");

            // 2. Get the value for the key
            string savedValue = await db.StringGetAsync(key);
            Console.WriteLine($"Get: {key} => {savedValue}");

            // 3. Set an expiration for the key
            TimeSpan expiryTime = TimeSpan.FromSeconds(10);
            await db.KeyExpireAsync(key, expiryTime);
            Console.WriteLine($"Set expiration for {key}: {expiryTime.TotalSeconds} seconds");

            // 4. Check key existence after expiration
            Console.WriteLine("\nWaiting for the key to expire...");
            await Task.Delay(12000); // Wait 12 seconds
            bool exists = await db.KeyExistsAsync(key);
            Console.WriteLine($"Key Exists After Expiration: {key} => {exists}");

            // Close the connection
            redis.Close();
            Console.WriteLine("\nAll Redis operations completed.");
        }
    }
}

Step 3. Run the Application.

To execute the application.

dotnet run

Expected Output

The program will connect to Redis, perform basic key-value operations, and validate key expiration. You should see output like this,

Install the StackExchange.Redis package for Redis connectivity.
dotnet add package StackExchange.Redis


How Redis Works with .NET Core?

Here’s what the application does step by step,

  1. Connects to the Redis server using ConnectionMultiplexer, which manages connection pooling and server communication.
  2. Performs basic commands.
    • StringSetAsync: Sets a key-value pair in Redis.
    • StringGetAsync: Gets the value of a key.
    • KeyExpireAsync: Sets an expiration time for a key.
    • KeyExistsAsync: Checks if a key exists.
  3. Handles temporary in-memory storage of data with expiration.

If you’re working in a Windows environment and prefer not to install a native Redis instance or use Docker, you can use a Redis-compatible server as an alternative.

Setting Up a Redis-Compatible Server
  • Install a Redis-compatible server for Windows.
  • Once installed, the server typically runs on localhost:6379 by default, similar to Redis.
  • Your application does not require any code changes to work with a Redis-compatible server.

Using a Redis-compatible server allows Redis functionality to run natively on Windows without relying on containers or virtualized environments.

Advantages of Using Redis in .NET Core
  1. Performance: Redis operates fully in memory, enabling extremely low latency.
  2. Ease of Use: Simplified API for common key-value needs, with additional data structures like lists, sets, and hashes.
  3. Flexibility: Redis serves multiple purposes (e.g., caching, message queues, pub/sub).
  4. Scalability: Redis supports clustering and high availability for scaling with demand.
Conclusion

Integrating Redis into your .NET Core application allows you to build high-quality, performant systems that can handle demanding workloads. With the StackExchange.Redis library, you can interact with Redis seamlessly.

Start by implementing Redis for simple caching or session management, and expand its usage to pub/sub and real-time data needs in your distributed .NET Core applications.

Happy coding and scaling!

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

How to Begin Using OpenCV in .NET?

Leave a Comment

One well-known open-source framework for image processing, computer vision, and machine learning is called OpenCV (Open Source Computer Vision Library). Although OpenCV has its origins in C++, OpenCvSharp, a.NET wrapper for the OpenCV library, offers bindings that enable it to be used with ease in.NET applications.

This article is a beginner-friendly guide to getting OpenCV up and running in your .NET environment, demonstrating a basic example: loading an image and converting it to grayscale.

Prerequisites

Before diving into code, ensure you have the following set up.

  1. Visual Studio (or any C# IDE of your choice).
  2. .NET 5, .NET 6, or higher installed on your system.
  3. Basic familiarity with C# and .NET projects.
1. Set Up OpenCvSharp in Your .NET Project

To use OpenCV in .NET, we'll install the OpenCvSharp NuGet package. This provides high-level bindings to OpenCV's functionality within a .NET application.

Steps to Install OpenCvSharp
  1. Create a New .NET Project: Create a new console application named OpenCVExample.
  2. Install the OpenCvSharp NuGet Packages: Run the following in your terminal or Package Manager Console in Visual Studio.
    dotnet add package OpenCvSharp4
    dotnet add package OpenCvSharp4.runtime.win  # For runtime support on Windows
2. Load an Image and Convert It to Grayscale

Now that OpenCvSharp is installed, let’s write a simple program that.

  1. Loads an image.
  2. Converts the image to grayscale.
  3. Displays the original and grayscale images.

Here’s the complete example.

Program Code

using System;
using OpenCvSharp;

class Program
{
    static void Main(string[] args)
    {
        // Path to the image file (change this to the path of your image file)
        string imagePath = "sample.jpg";
        // Step 1: Load the image
        Mat inputImage = Cv2.ImRead(imagePath, ImreadModes.Color);
        if (inputImage.Empty())
        {
            Console.WriteLine("Failed to load the image. Check the file path.");
            return;
        }
        Console.WriteLine("Image loaded successfully!");
        // Step 2: Convert the image to grayscale
        Mat grayImage = new Mat();  // Create a new matrix to store the grayscale image
        Cv2.CvtColor(inputImage, grayImage, ColorConversionCodes.BGR2GRAY);
        Console.WriteLine("Image converted to grayscale.");
        // Step 3: Display both images (original and grayscale)
        Cv2.ImShow("Original Image", inputImage);
        Cv2.ImShow("Grayscale Image", grayImage);
        // Wait for a key press before closing the image display windows
        Console.WriteLine("Press any key to close the image windows.");
        Cv2.WaitKey();
        Cv2.DestroyAllWindows();
    }
}
3. Run the Application

Steps

  1. Add the Image File: Place the image (sample.jpg) in the bin\Debug\net8.0 project folder, or specify the absolute path to your image file.
  2. Build and Run the Code: Press Ctrl + F5 in Visual Studio or run from the terminal.
  3. Result
    • Two separate windows will open.
      • One shows the original image.
      • One shows the grayscale version.
    • The console will display messages about the image processing status.
4. Key Methods and Concepts

Let’s break down some essential parts of the code.

(i) CV2.ImRead(): Load an Image
  • Loads the image from the path specified.
  • The second parameter specifies the color mode.
    • ImreadModes.Color (default): Loads in color (BGR format).
    • ImreadModes.Grayscale: Directly loads the image as grayscale.
(ii) Cv2.CvtColor(): Color Conversion
  • Converts an image from one format to another.
  • In our example, we convert the original image (in BGR format) to grayscale.
    Cv2.CvtColor(inputImage, grayImage, ColorConversionCodes.BGR2GRAY);
(iii) CV2.ImShow(): Display an Image
  • Creates a window and displays the image.
  • Parameters
    • Window Name: Unique name for the display window.
    • Image: The Mat object (photo) to display.
(iv) CV2.WaitKey() and Cv2.DestroyAllWindows()
  • Cv2.WaitKey() pauses the execution and keeps the image windows open until a key is pressed.
  • Cv2.DestroyAllWindows() closes all image display windows once you're done.
5. Next Steps

Now that you've successfully loaded and processed your first image with OpenCV in .NET, the possibilities are endless! Here are some recommended next steps.

Step 1. Try with Other Image Processing Functions.

Explore methods such as blurring, edge detection, and thresholding. Examples include,

  • Cv2.GaussianBlur(): Apply a Gaussian blur to an image.
  • Cv2.Canny(): Perform edge detection.

Example of detecting edges in a grayscale image.

Mat edges = new Mat();
// Edge detection with thresholds
Cv2.Canny(grayImage, edges, 100, 200);
Cv2.ImShow("Edge Detection", edges);

Step 2. Handle Videos.

Use VideoCapture from OpenCV to process video files or webcam streams.

Step 3. Explore Image Manipulations.

  • Cropping
  • Rotating
  • Resizing images

Step 4. Utilize Object Detection Filters.

Explore advanced topics such as object detection, face recognition, or feature extraction.

Conclusion

Congratulations! You’ve taken your first steps in using OpenCV with .NET through OpenCvSharp. Loading an image and converting it to grayscale is a foundational exercise, setting the stage for more advanced operations, such as image enhancements, object detection, or deep learning integrations.

By adding OpenCV to your software development toolkit, you unlock a world of possibilities for building applications in image processing, computer vision, and beyond. So, keep experimenting and take your application development to the next level!

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 10.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/

Read More

SQL Server Integration in Aspire Applications: .NET Aspire Integrations

Leave a Comment

Databases, caches, message brokers, APIs, telemetry systems, and other supporting technologies are all essential to modern cloud-native applications. Writing business logic is only one aspect of creating such an application; another is carefully connecting these services in a scalable, observable, and maintainable manner. By providing a strong application model that makes it simple for developers to create, set up, and maintain service dependencies,.NET Aspire reduces this complexity.

What do Aspire Integrations bring to the Table?

When you add an integration to an Aspire project, you get.

  • Typed configuration and DI setup: Auto-wiring of client libraries with configuration via strongly typed options.
  • Health checks: Automatic inclusion of health checks for critical dependencies.
  • Connection string propagation: Seamless sharing of connection strings across projects using Aspire's service discovery.
  • Dashboard visibility: Integrated resources are visible and traceable through the Aspire Dashboard.
  • Simplified Dev Experience: You don’t have to manually set up service bindings or write boilerplate configuration.

These integrations promote a cloud-native design, while also making local development and testing smoother and more predictable.

Common Integrations in .NET Aspire

.NET Aspire comes with official and community-supported packages that make integrating third-party services a breeze. Below is a curated list of popular tools and services across different categories that work seamlessly with Aspire.

Databases
Service Integration Package Notes
SQL Server Aspire.Hosting.SqlServer Connection string, health check, and discovery are handled automatically.
PostgreSQL Microsoft.Extensions.Hosting.PostgreSql Community-supported; connection string injection.
MySQL Microsoft.Extensions.Hosting.MySql Similar benefits to PostgreSQL.

Caching & Data Store
Service Integration Package Notes
Redis Microsoft.Extensions.Caching.StackExchangeRedis.Aspire Adds Redis as a resource, injects connection string, auto configures.
MongoDB MongoDB.Driver.Aspire (community) Mongo client setup via Aspire DI.

Messaging & Eventing
Service Integration Package Notes
RabbitMQ Tye.Hosting.RabbitMQ.Aspire (community) Easy messaging setup.
Azure Service Bus Microsoft.Azure.ServiceBus.Aspire (planned) Advanced integration expected in future releases.

Observability & Monitoring
Tool Integration Package Notes
OpenTelemetry Microsoft.Extensions.Telemetry.Aspire Auto-wires tracing/metrics.
Grafana + Prometheus Community Templates Can export Aspire metrics here.

External Services & APIs
Type Example Aspire Support Notes
HTTP APIs REST, GraphQL, gRPC APIs Use .WithEndpoint() to define upstream APIs.
Cloud SDKs Azure, AWS Aspire config + DI bindings are supported manually.

.NET Aspire SQL Server integration

Let’s see in action how to get an Aspire Integrations with SQL Server.

When building distributed applications, a database is often a critical component.

.NET Aspire simplifies integrating SQL Server into your project by providing first-class support through its Aspire.Hosting.SqlServer package.

This integration focuses on,

  • Spinning up SQL Server instances (locally or containerized) during development.
  • Managing connection strings automatically.
  • Sharing database endpoints across your application components.
  • Adding health checks for SQL Server availability.
  • Visualizing the SQL Server resource in the Aspire Dashboard.
Setting Up SQL Server Integration

Step 1. Install the SQL Server Aspire Package.

In your AppHost project, run.

dotnet add package Aspire.Hosting.SqlServer

Or simply visit to manage NuGet Packages and “Aspire.Hosting.SQLServer” in App Host.


This package brings in the AddSqlServer extension method that makes adding SQL easy.

Step 2.
Define the SQL Server Resource.
In your Program.cs inside the AppHost project.

SQL Server Resource

Here is what this code does.

  1. Define a parameter for the SQL Server password.
    IResourceBuilder<ParameterResource>? dbPassword =
        builder.AddParameter("dbPassword", true);

Key Points in This Setup

  • AddParameter("dbPassword", true): Securely prompts for the database password if it's not already configured.
  • AddSqlServer("sql", dbPassword, 1455): Adds a SQL Server resource running on custom port 1455 and uses the provided password.
  • .WithLifetime(ContainerLifetime.Persistent): Ensures the SQL Server container persists between runs.
  • AddDatabase("database"): Defines a database inside SQL Server for use by the application.
  • .WithReference(db) and .WithReference(MyAPI): Links services together by passing resources like connection strings automatically.

Step 3. Configure Parameters Securely.

Instead of hardcoding sensitive information like database passwords in your code, Aspire encourages you to use Parameters.

In your appsettings.json, define the SQL Server password under the Parameters section.

  • dbPassword is injected at runtime into the SQL Server resource.
  • You can also override it using environment variables or secret managers for production.
  • This keeps your applications secure, configurable, and environment-agnostic.

Important. If the “dbPassword” is not found in your settings or environment, Aspire will prompt you to enter it at startup (because of the true flag in AddParameter("dbPassword", true)).

Pro Tip. Managing Sensitive Parameters in .NET Aspire Applications.

  • Never hardcode secrets like passwords directly in code files.
  • Prefer appsettings.json for local development, but move to secret managers like Azure Key Vault or environment variables in production.
  • Use AddParameter with isSecret: true to ensure Aspire handles the value securely, and prompts when missing.
  • Do not commit real secrets into your source control repositories (e.g., GitHub).
  • Leverage dotnet user-secrets for development.
    dotnet user-secrets set "Parameters:dbPassword" "YourSecurePassword"
  • Configure deployment environments to provide required parameters securely during CI/CD pipeline runs.
Aspire Dashboard View

When you run the application, the Aspire Dashboard will show your SQL Server alongside your services, making the architecture and dependencies crystal clear.

Example

[SQL Server] <--- connected to ---> [Web API]
Aspire Dashboard View

When you run the application, the Aspire Dashboard will show your SQL Server alongside your services, making the architecture and dependencies crystal clear.

Example

[SQL Server] <--- connected to ---> [Web API]
SQL

Step 1. SQL Server and Database Creation Verification.

  • Open your application in the Aspire Dashboard (localhost:17010).
  • In the Resources tab, you will see a list of services.
  • Notice two services.
    • SQL (SQL Server): Running state with the source pointing to mcr.microsoft.com/mssql/server2022-latest.
    • Database: Running state.

  • These were automatically created based on the definitions provided in your Program.cs file.
  • The SQL Server service is configured to expose on tcp://localhost:1455, as per the given port number.

Step 2. Verifying API Environment Variables

  • In the Aspire Dashboard, under Resources, locate the API service.
  • Click the three dots (...) next to the API service.
  • Select View details from the dropdown menu.

Step 3. Checking the Database Connection String.

  • In the Project: API details view, scroll to the Environment Variables section.
  • Look for the environment variable named: ConnectionStrings__database.
  • You will find the database connection string, such as Server=127.0.0.1,1455;User ID=sa;Password=Nit1n5QL;
  • This confirms that the API service has the database connection string injected correctly through environment variables.

Step 4. Aspire Action Reflected in Docker (Local).

You can see the side effects of Aspire's local work in Docker Desktop.

  • Images: An image mcr.microsoft.com/mssql/server:2022-latest is pulled into Docker.
  • Containers: A container sql-xxx is running, exposing the SQL Server on port 1455.

Result: Aspire used Docker to spin up the local SQL server dynamically for your app.

Area Action by Aspire Result Seen Where
Database Server SQL Server container created on port 1455 Docker Desktop (Containers tab)
Database Resource Database initialization or setup done Aspire Dashboard - Resources
API Env Setup Database connection string injected automatically Aspire Dashboard - API - Environment Variables
Docker Image MSSQL Image pulled if not present Docker Desktop (Images tab)

Debugging the Connection String: Verify reading the environment variables

Let’s try reading the Connection string from the environment variables, As we have added the reference of SQL Server database to the Weather API Project from App host with Aspire Hosting.

To do that I have added a code to read the connection string from application configuration variables with the name “database” in my API Controller’s Get method “GetWeatherForecast”:

Run the solution and open API swagger to hit the API End Point for debugging the code with a breakpoint on the same line.

You can see the connection string is available for the API Project from the application configurations even though we don’t have any local parameter the name of “database”.

Here is the connection string we got.

Server=127.0.0.1,1455;User ID=sa;Password=Nit1n5QL;TrustServerCertificate=true;Initial Catalog=database

Testing in SSMS

If you want you can use the same connection string in the SQL Server Management Studio to check this Database and its table, which may help you inthe future.

Paste the same connection String in the last tab “Additional Connection Parameters” and hit connect.

I am sure you must be able to see the connected Server and Database in SSMS’s Object Explorer.

Why Use SQL Server Integration with Aspire?
Benefit Description
Fast Setup No manual container configuration is needed.
Secure Connection Management Credentials and connection strings are injected safely.
Automatic Health Monitoring Built-in health checks for SQL Server connectivity.
Easy Switching Easily swap local dev SQL Server with Azure SQL for production.

Similarly, you can use Aspire Immigrations for Databases and other tools.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

A Brief Introduction to SignalR in.Net Core

Leave a Comment

These days, people expect apps to updates in real-time like live chats, notifications, or game scores, without refreshing the page again and again. SignalR in .NET Core helps you do just that by making real-time communication easy. In this blog, we’ll quickly show you how to get started with it in your own .NET Core project.

SignalR: What is it?

Microsoft created the SignalR real-time messaging library, which enables two-way communication between clients—such as desktop programs, mobile apps, or web browsers—and the server. Adding real-time functionality to your web apps is simple and scalable, allowing users to get updates and notifications quickly without requiring manual requests or page refreshes.

Usages of SignalR

Here are some common use cases where SignalR can be a great fit for adding real-time functionality to your applications.

  • Chat Applications: SignalR is perfect for building mid-level chat applications where users can exchange messages instantly. It supports sending messages to all users, specific groups, or individual users in real-time. For a higher-level chatting application, XMPP or WebSocket is the best option.
  • Notifications: You can use SignalR to push real-time notifications to users for events such as new messages, system alerts, or order updates without making them refresh the page.
  • Live Dashboards: For use cases like monitoring systems or admin panels, SignalR enables real-time dashboards that automatically refresh as data changes, helping users make quick decisions.
  • Online Exams or Quizzes: SignalR can be used in online test platforms to push time updates or instant results to participants during live sessions.
  • Live Polls and Q&A: Apps that conduct live polls or Q&A during webinars or events can benefit from SignalR by showing real-time responses and updates to all viewers instantly.
  • Collaboration Tools: SignalR is again helpful in mid-level collaborative apps where multiple users need to work together in real-time—like document editing, whiteboards, or project tracking tools.
How to use in an ASP.NET Core project?

To use in a .NET Core project, you have to install the SignalR NuGet package. Run the below command from NuGet Package Manager or PowerShell

# .NET CLI
dotnet add package Microsoft.AspNet.SignalR

# Nuget Package Manager
NuGet\Install-Package Microsoft.AspNet.SignalR
Bash

Now you have to create a Hub. Let's say we are building a chatbot using SignalR; hence, we are creating a chat hub. This hub will handle the server-side logic for sending messages.

// ChatHub.cs
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

Next, we have to register ChatHub in the program.cs file so that it can initialize at the time of starting.

// program.cs

var builder = WebApplication.CreateBuilder(args);

// Register services
builder.Services.AddRazorPages();
builder.Services.AddSignalR(); // Register SignalR

var app = builder.Build();

// Configure middleware
app.UseStaticFiles();
app.UseRouting();

// Map endpoints
app.MapRazorPages();
app.MapHub<ChatHub>("/chathub"); // Map Chathub with an endpoint

app.Run();
How to use in Front-end projects?

As our backend code is reday. Now let's use this in the frontend. Either you can use CDN script of SignalR or npm package of SignalR in case of Angular, React, or Next JS like below.

Using CDN

<!-- CDN for SignalR -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.5/signalr.min.js"></script>

<script>
    // Setting up the endpoint
    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/chathub")
        .build();

    connection.on("ReceiveMessage", (user, message) => {
        const msg = `${user} - ${message}`;
        const li = document.createElement("li");
        li.textContent = msg;
        document.getElementById("messagesList").appendChild(li);
    });

    connection.start()
        .catch(err => console.error(err.toString()));

    document.getElementById("sendButton").addEventListener("click", () => {
        const user = document.getElementById("userInput").value;
        const message = document.getElementById("messageInput").value;

        connection.invoke("SendMessage", user, message)
            .catch(err => console.error(err.toString()));
    });
</script>
Using an NPM package in Angular

To use in Angular, you have to install the SignalR npm package

npm install @microsoft/signalr

Then have to create a service for the communication.

/* signalr.service.ts */

import { Injectable } from '@angular/core';
import * as signalR from '@microsoft/signalr';

@Injectable({
  providedIn: 'root'
})
export class SignalrService {
  private hubConnection: signalR.HubConnection;
  public messages: string[] = [];

  public startConnection(): void {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl('http://localhost:5000/chathub') // URL to be fetched from environment config
      .build();

    this.hubConnection
      .start()
      .then(() => console.log('Connection started'))
      .catch(err => console.log('Error while starting connection: ' + err));

    this.hubConnection.on('ReceiveMessage', (user: string, message: string) => {
      this.messages.push(`${user}: ${message}`);
    });
  }

  public sendMessage(user: string, message: string): void {
    this.hubConnection.invoke('SendMessage', user, message)
      .catch(err => console.error(err));
  }
}

And now it's time to consume this service from a component.

/* app.component.ts */
/* In the blog app.component has been used. In actual project, please create a new component and register */

import { Component, OnInit } from '@angular/core';
import { SignalrService } from './signalr.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
  user = '';
  message = '';

  constructor(public signalRService: SignalrService) {}

  ngOnInit(): void {
    this.signalRService.startConnection();
  }

  sendMessage(): void {
    this.signalRService.sendMessage(this.user, this.message);
    this.message = '';
  }
}

In the HTML, place the text box & div to view the messages.

<!-- app.component.html -->

<div>
  <input [(ngModel)]="user" placeholder="Your name" />
  <input [(ngModel)]="message" placeholder="Message" />
  <button (click)="sendMessage()">Send</button>

  <ul>
    <li *ngFor="let msg of signalRService.messages">
      {{ msg }}
    </li>
  </ul>
</div>
Architectural components of SignalR

Now, as you know how to use SignalR, let's also deep dive into the architectural components of SignalR. Here are the main parts that make up the SignalR setup.

  • Hubs: A Hub is a central part of SignalR that manages communication between the server and connected clients. It takes care of handling connections, sending messages, and converting data formats. With Hubs, clients can call server-side methods, and the server can also call methods on the clients.
  • Clients: Clients are applications or devices, such as browsers or mobile apps, that connect to the SignalR server to exchange real-time messages. Using the SignalR client library, these clients can easily send messages to the server and receive updates without delay.
  • Transports: SignalR uses different methods, called transports, to create and maintain the connection between the client and the server. These include WebSockets, Server-Sent Events (SSE), Long Polling, and Forever Frame, depending on what the client and server support.
  • Connections: A connection refers to the link between a single client and the SignalR server. Each connection has a unique ID that keeps track of the client and sends messages to the right one.
  • SignalR Server: The SignalR server handles all the communication between clients. It manages connections, routes messages to the right clients, and controls the flow of data through the pipeline.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/

 

Read More
Previous PostOlder Posts Home