What is .NET Aspire? Transforming Cloud-Native App Development
Friday, January 10, 2025There was a time when building resilient, observable, and easy-to-maintain distributed applications seemed like a distant dream. But not anymore. Microsoft launched Aspire, a new addition to the .NET ecosystem, as an effective solution to simplify the development of cloud-based and distributed applications.
Now, an expert .NET development company can easily leverage this tech stack to build robust and fully-featured cloud-native applications. Released in November 2023, Aspire is already making significant waves in the community.
This article provides an understanding of what is .NET Aspire, as well as discovers its features and benefits. It also includes a step-by-step guide to .NET Aspire app development.
1. Understanding .NET Aspire
.NET Aspire is a comprehensive solution that supports the development of cloud-native applications, improving the overall developer experience in the .NET ecosystem. It focuses on key aspects such as tooling, configuration, service discovery, component integration, and orchestration to overcome cloud-native challenges.
Developing and maintaining observable, production-ready distributed apps becomes easier, as it offers a cohesive suite of tools and design patterns.
Aspire allows you to easily set up multiple small projects with related components, especially if it includes Azure resources. This cloud-ready stack feature enables you to build apps with common resources. As a result, you can develop and deploy .NET cloud-native applications with improved efficiency and consistency.
Here is what a Twitter user says about it.
2. Key Features of. Net Aspire
Knowing the features of .NET Aspire would provide a better understanding of this toolset and how it works. Some of its fundamental features include:
2.1 Application Templates
It provides a wide range of project templates and includes the .NET Aspire starter app, enabling the developers to easily create applications using Visual Studio, Visual Studio Code, and the .NET CLI.
2.2 Microservice Support
.NET Aspire uses a microservices architecture. This allows developers to break down complex apps into small, independent services that are easy to deploy and maintain.
2.3 Unified Development Environment
It supports robust IDEs like Visual Studio and Visual Studio Code that support multiple .Net programming languages like VB.NET, F#, and C#. As a result, .NET programmers can enjoy a seamless development experience.
2.4 Components
.NET Aspire provides an easy method to use NuGet packages in different services such as PostgreSQL and Redis. Several NuGet packages related to Aspire are available for direct installation. With these packages, you can easily integrate and configure services in your application and use the established methods to address cloud-related issues.
Given below is a two-step process, showing you how to add a Redis component in your application.
- Add the NuGet package to your project.
- The AddRedis methods will automatically update the AppHost program.cs.file.
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddRedis("cache");
var apiService = builder.AddProject("apiservice");
builder.AddProject("webfrontend")
.WithExternalHttpEndpoints()
.WithReference(cache)
.WithReference(apiService);
builder.Build().Run();
3. Benefits of .NET Aspire
New features and improved cloud capabilities of .NET Aspire offer numerous benefits. Some of them are as mentioned below:
3.1 Productivity
.NET Aspire automates various tasks related to handling and configuring cloud-native apps. So that developers can focus more on writing business logic and deploying better features. This helps increase overall developer productivity.
3.2 Enhanced Developer Toolkit
It provides app templates like the .NET Aspire starter app and .NET Aspire application to simplify the .NET app development process. With this wide range of ready-made project templates, it becomes easy for designers to create apps in Visual Studio or .NET CLI.
3.3 Simplifying Cloud Development
Setting up multiple cloud services can be challenging. But .NET Aspire makes it easy by providing you with a standardized environment where everything is already set up to get started. There is no need to waste time on technical details; you can just focus on creating features that meet expectations.
For example, To create an order management application, you need a Redis cache, an ASP.NET Core API, and a Blazor front-end. Setting up all these components can be overwhelming and time-consuming. But .NET Aspire simplifies the process with pre-configured templates, allowing you to set everything up and get started within a few minutes.
3.4 Focus On Core Functionality
.NET Aspire is a leader in cloud-native development. It manages all the complexities of your project in the background, allowing you to focus on building the core functionalities of your .NET applications.
3.5 Monitoring All Components Together
One of the biggest advantages of using .NET Aspire is its monitoring capabilities. It allows you to monitor the entire distributed application from a single place of convenience in a user-friendly way.
You can monitor the live status of every service and view all the logs, traces, and metrics. Simply go to the intuitive menu and select the commonly used services using their human-readable names.
4. Prerequisites
Before you get started working with the .NET Aspire, make sure you have the following things installed in your system.
- .NET 8
- .NET Aspire Workload
- Docker Desktop
- Visual Studio 2022 Preview
5. Creating Your First .NET Aspire Project
Here, in this blog, we show you how to create a .NET Aspire application using two different templates from Visual Studio 2022.
5.1 Steps for Creating your first .NET Aspire Starter Project
1. Open Visual Studio 2022 Preview and search for the .NET Aspire Starter Application template. Pick an appropriate option that suits your project requirements.
2. Enter a proper name and location for your new project in their respective fields. Click on “Next” and continue with the default target framework.
3. Once you complete creating a new project, your screen will show you the following .net projects (see below image for reference):
- ApiService: It’s a backend API provider that manages requests and responses between front-end web applications and databases or other services. It ensures efficient processing and communication by handling business logic and data access.
- AppHost: Every project execution that takes place in the .NET Aspire application is coordinated by AppHost. It also handles configuration settings and dependencies. AppHost ensures seamless integration between different components.
- ServiceDefaults: This component is responsible for managing dependencies and configuration across the .NET application. Adopting a standard approach, ServiceDefaults configures services to maintain and scale the application easily.
- Web: Serving as a front-end interface, the Web component uses Blazor to communicate with the ApiService. It also handles user interactions by fetching data from the backend and displaying it on the screen. This helps build responsive UI and deliver a seamless user experience.
4. You can view the .NET Aspire Dashboard after starting the project. The dashboard helps you monitor different aspects of the application such as projects, containers, executables, logs, traces, and metrics.
- Project: All microservices are listed as projects on your dashboard
- Container: Displays supporting services such as Redis caches.
- Executable: Shows the components that serve as Executables.
- Console Logs: Displays the tests that are sent as standard output for status messages or events.
- Structured Logs: Shows the logs in table format with basic filters, search, and log level adjustments. Clicking on the View button will provide more details on the log.
- Endpoints: Lists Endpoints for microservices to enable direct connection and testing in the browser.
- Traces: It tracks all the request paths across your application.
- Metrics: Shows all the exposed meters and instruments along with their dimensions.
5. The resources section on your screen provides important information about all of your projects saved in the .NET Aspire Setup.
6. With the help of left-side navigation, you can visit the weather page to find all the weather-related data.
6. Creating a .NET Aspire Application
1. Open the Visual Studio 2022 and select the .NET Aspire Application option from the list.
2. Give an appropriate solution name for your new project.
3. Your project solution has the options for AppHost and ServiceDefaults on the right side of the screen as shown in the image below:
4. Add a new Web API project to the solution.
5. Add a new Blazor Web App project to the solution.
6. After adding both the Web API application and the Blazor web app to your solution, it looks like:
7. Now, add a new Model file for Time Entry in the Web API project.
namespace AppAspireAPI
{
public class TimeEntry
{
public int Id { get; set; }
public DateTime? date { get; set; }
public string description { get; set; }
}
}
8. Also, add an API Controller in the Web API project.
using Microsoft.AspNetCore.Mvc;
namespace AppAspireAPI.Controllers
{
[ApiController]
[Route("/api/[controller]")]
public class TimeEntriesController : Controller
{
private static readonly List timeEntries = new List();
[HttpGet]
public ActionResult> Get()
{
return Ok(timeEntries);
}
[HttpPost]
public ActionResult Post([FromBody] TimeEntry timeEntry)
{
if (string.IsNullOrEmpty(timeEntry.description.Trim()))
{
return BadRequest("Description cannot be empty.");
}
timeEntries.Add(timeEntry);
return Created();
}
[HttpDelete("{id}")]
public ActionResult Delete(int id)
{
if (id timeEntries.Count - 1)
{
return NotFound("Time Entry not found.");
}
timeEntries.RemoveAt(id);
return Ok("Time Entry removed Successfully");
}
}
}
9. Making changes in the Program.cs.file in the AppHost project as shown in the above image allows you to add the web app and API application for the Aspire app.
var builder = DistributedApplication.CreateBuilder(args);
var webapi = builder.AddProject("webapi");
builder.AddProject("webapplication").WithReference(webapi);
builder.Build().Run();
10. Create a record object to retrieve and send the API data in the Web Project.
namespace AppAspireWeb
{
public record TimeEntry(int Id, string description, DateTime? date)
{
}
}
11. Create a Service class to communicate with the API in the Blazor web project.
namespace AppAspireWeb.Services
{
public class TimeEntriesService
{
private readonly HttpClient _httpClient;
public TimeEntriesService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task> GetTimeEntriesAsync()
{
return await _httpClient.GetFromJsonAsync>("/api/TimeEntries");
}
public async Task PostTimeEntryAsync(string description, DateTime? date)
{
await _httpClient.PostAsJsonAsync("api/TimeEntries", new TimeEntry(0, description, date));
}
public async Task DeleteTimeEntryAsync(int id)
{
await _httpClient.DeleteAsync($"/api/TimeEntries/{id}");
}
}
}
12. The http client from Time Entries API would prefer https over http once you add the above code in the Program.cs.file in the Blazor web app.
// Add api services
builder.Services.AddHttpClient(client =>
{
// prefer https over http for api
client.BaseAddress = new("https+http://webapi");
});
13. Add the TimeEntries UI page in the Blazor application.
@page "/timeEntries"
@using AppAspireWeb.Services
@rendermode InteractiveServer
@inject TimeEntriesService timeEntryService
TimeEntries
@if (timeEntries != null && timeEntries.Count > 0)
{
Action
Date
Description
@foreach (var entry in timeEntries)
{
@(entry.date != null ? entry.date?.ToString("dd/MM/yyyy") : "")
@entry.description
}
}
else
{
Action
Date
Description
No Records Found
}
@code {
private List timeEntries = new List();
private string description = string.Empty;
private DateTime? selDate;
protected override async Task OnInitializedAsync()
{
await LoadTimeEntries();
}
public async Task LoadTimeEntries()
{
timeEntries = await timeEntryService.GetTimeEntriesAsync();
}
public async Task AddTimeEntry(){
await timeEntryService.PostTimeEntryAsync(description, selDate);
description = string.Empty;
selDate = null;
await LoadTimeEntries();
}
public async Task RemoveTimeEntry(int id)
{
if (id > -1){
await timeEntryService.DeleteTimeEntryAsync(id);
await LoadTimeEntries();
}
}
}
14. After executing the project with the run( demonstration ) command, you can see the output in the following images.
Project dashboard view:
Backend view:
Frontend view:
7. Conclusion
Microsoft is dedicated to making .NET the most effective and hassle-free solution for building cloud-native applications. Designing .NET Aspire was a significant step in this way. It’s a tool stack that not only handles operational elements of the app but helps with actual development. To fulfill this role, it offers a wide array of features including telemetry, service discovery, and monitoring, components, and health checks.
We discussed some of the important features in this blog and explored how we can build apps using this robust tech stack in real life. Now, it is safe to say that cloud-native app development is no longer difficult, thanks to .NET Aspire.
FAQs
What is the difference between NET Core and NET Aspire?
Microsoft created .NET Core as a general-purpose platform. Meanwhile, .NET Aspire was specially designed for building cloud-native microservices and distributed applications.
Is .NET Aspire only for Azure?
When it comes to Azure deployment, .NET Aspire does provide first-party solutions. But that’s not a necessity. Being a cloud-native stack, it helps to develop apps that can run anywhere. .NET Aspire’s Azure capabilities are one of its cloud offerings.
Comments