这是用户在 2024-8-9 11:28 为 https://devblogs.microsoft.com/dotnet/adding-dotnet-aspire-to-your-existing-dotnet-apps/ 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?

Adding .NET Aspire to your existing .NET apps
将 .NET Aspire 添加到现有的 .NET 应用程序中

Jon Galloway 乔恩-加洛韦

.NET Aspire is a new cloud-ready stack tailored for .NET, enabling developers to quickly and easily develop distributed applications. You’ve probably seen demos showing large .NET solutions with lots of fancy cloud dependencies and thought, well, maybe I’d use that someday if I’m starting on a giant enterprise Redis Kafka Postgres cloud-a-ganza, but it’s not really something I can use today.
.NET Aspire 是为 .NET 量身定制的全新云就绪堆栈,使开发人员能够快速、轻松地开发分布式应用程序。你可能看过一些演示,展示了带有大量花哨的云依赖关系的大型 .NET 解决方案,然后你会想,如果有一天我开始开发一个巨大的企业级 Redis Kafka Postgres 云平台,也许我会用到它,但现在我还用不上。

But .NET Aspire is not just about cutting-edge technology and green-field apps; it’s also about making your current applications more straightforward. With .NET Aspire, you can streamline the startup process, improve monitoring, and increase the reliability of your applications. Plus, you can use service discovery to enhance your apps, even if you’re not ready to use more complex features or services like Redis or containerized deployment.
但是,.NET Aspire 不仅仅是尖端技术和全新应用程序,它还能使您当前的应用程序更加简单明了。通过 .NET Aspire,您可以简化启动过程、改进监控并提高应用程序的可靠性。此外,即使您还没有准备好使用更复杂的功能或服务(如 Redis 或容器化部署),您也可以使用服务发现来增强您的应用程序。

In this post, we’ll look at how easy it is to make your existing solutions better – just easier to maintain and add the kind of features you’re already working on. And, sure, it’s nice that you can more easily integrate more sophisticated cloud dependencies and features… but even if you never do it’s still a win.
在这篇文章中,我们将探讨如何轻松地改进现有解决方案--只需更轻松地维护和添加您正在开发的功能。当然,您可以更轻松地集成更复杂的云依赖关系和功能,这固然很好......但即使您从未集成过,这也是一种胜利。

TLDR: In under 5 minutes you can add .NET Aspire to your existing apps and get a dashboard, health checks, and more… all without changing how your apps work, your CI/CD pipeline, or deployment process.
简要说明:只需不到 5 分钟,您就可以将 .NET Aspire 添加到现有应用程序中,并获得仪表板、健康检查等功能......所有这一切都无需改变应用程序的工作方式、CI/CD 管道或部署流程。

What even is .NET Aspire?
什么是 .NET Aspire?

If you ask five people, you will most likely get five different answers. Honestly, it’s a little hard to describe, and attempts to do it briefly can turn into a bit of buzzword bingo. Really, it’s just a way to solve a problem: building distributed applications is hard. Even just running your app requires starting up one or more services and a front-end and making sure they can talk to each other can be frustrating. Wouldn’t it be nice if that was easier? That is what .NET Aspire aims to do, be your building blocks for your distributed applications making them more observable, resilient, scalable, and manageable.
如果你问五个人,很可能会得到五个不同的答案。老实说,要描述分布式应用有点困难,试图简短地描述它可能会变成有点拗口的 "宾果游戏"。实际上,它只是一种解决问题的方法:构建分布式应用很难。即使只是运行应用程序,也需要启动一个或多个服务和前端,并确保它们能够相互通信,这也会令人沮丧。如果能让这一切变得更简单,岂不更好?这就是 .NET Aspire 的目标,它将成为您的分布式应用程序的构建模块,使它们更具可观察性、弹性、可扩展性和可管理性。

Let’s take a look at how a lot of applications evolve over time. A lot start as a single monolithic proof of concept. You’ve got an app with a database.
让我们来看看许多应用程序是如何随时间演变的。很多应用程序一开始只是一个单一的概念验证。你有一个带有数据库的应用程序。

Diagram of a simple app with a Blazor front end connected to a data source

Assuming your proof of concept is successful, just about every modern app evolves to include at least a front and back-end, in addition to the database.
假设您的概念验证成功,几乎每个现代应用程序都会发展到至少包括前端和后端,以及数据库。

Diagram - frontend-backend-database

And then, maybe, if our app’s usage and functionality keeps growing over time, the app will become really distributed, relying on a large set of distributed dependencies.
也许,随着时间的推移,如果我们应用程序的使用量和功能不断增加,应用程序就会变得真正的分布式,依赖于大量的分布式依赖关系。

Diagram - distributed

But here’s the important thing! Even in the really simple Proof Of Concept phase, and definitely in the Frontend-Backend-Database phase, we can benefit from .NET Aspire! With just a few lines of code, and without messing with our CI or deployment, we can really simplify our day-to-day developer experience.
但重要的是即使是在非常简单的概念验证阶段,肯定是在前台-后台-数据库阶段,我们也能从 .NET Aspire 中受益!只需几行代码,无需中断 CI 或部署,我们就能真正简化日常开发体验。

Step 1: Turn on .NET features we’ve been too busy to turn on with ServiceDefaults
第 1 步:使用 ServiceDefaults 打开我们一直忙得没时间打开的 .NET 功能

The ASP.NET Core team has been lighting up features for cool features for things like tracing, health checks, and resiliency for years. I’ve done half a dozen conference talks on “The One Hour ASP.NET Makeover” where we just turn on and configure all these cool features that have been in the box for years. But here’s the thing… it takes an hour to do that talk, after reading the docs and practicing! What if I could just flip an “Enable Pro Mode” switch instead?
多年来,ASP.NET Core 团队一直在为跟踪、健康检查和弹性等很酷的功能点亮功能。我已经在 "ASP.NET 一小时改造 "会议上做了六次演讲,在演讲中,我们打开并配置了所有这些已经存在多年的酷功能。但问题是......在阅读文档和练习之后,要花一个小时才能完成演讲!如果我只需打开一个 "启用专业模式 "开关,会怎样呢?

That’s what Service Defaults does for you. You can just turn on Service Defaults and you’ve got smart logging, health checks, resiliency, etc. based on what the .NET team recommends for ASP.NET Core apps and services. If you want, you can easily edit the Program.cs file in the ServiceDefaults project, but you don’t have to. Just turn it on.
这就是服务默认设置为您提供的功能。您只需打开 Service Defaults,就能根据 .NET 团队为 ASP.NET Core 应用程序和服务推荐的内容,获得智能日志记录、健康检查、弹性等功能。如果您愿意,可以轻松编辑 ServiceDefaults 项目中的 Program.cs 文件,但不必这样做。只需打开即可。

Adding a ServiceDefaults project
添加 ServiceDefaults 项目

Let’s look at an example with a simple Frontend – Backend app. I’ll use Jeff Fritz’s new MyWeatherHub sample from the Let’s Learn .NET Aspire event series, starting with the start-with-api code.
让我们来看一个简单的前台-后台应用程序示例。我将使用 Jeff Fritz 在 Let's Learn .NET Aspire 系列活动中发布的 MyWeatherHub 示例,从使用 api 代码开始。

Opening the solution, we’ll see that we’ve got two projects:
打开解决方案,我们会看到有两个项目:

  • MyWeatherHub – Web front-end project which displays live weather data
    MyWeatherHub - 显示实时天气数据的网络前端项目
  • API – Minimal API project which exposes live weather data from the US National Weather Service via a set of HTTP API endpoint
    API - 最小化应用程序接口项目,通过一组 HTTP 应用程序接口端点提供美国国家气象局的实时天气数据

Let’s add Service Defaults to this solution so we get health checks, logging, and other recommended features to both our front and back ends.
让我们将服务默认设置添加到此解决方案中,这样我们就能在前端和后端都获得健康检查、日志记录和其他推荐功能。

In Visual Studio 2022 or Visual Studio Code with the C# Dev Kit installed, here’s all we need to do:
在安装了 C# Dev Kit 的 Visual Studio 2022 或 Visual Studio Code 中,我们需要做的就是这些:

  1. Right-click on the solution and select Add > New Project.
    右键单击解决方案,选择添加 > 新项目。
  2. Select the .NET Aspire Service Defaults project template.
    选择 .NET Aspire 服务默认设置项目模板。
  3. Name the project ServiceDefaults (any name would work if you’re feeling creative, but the instructions in this post assume you’re using ServiceDefaults).
    将项目命名为 ServiceDefaults(如果你觉得有创意,任何名字都可以,但本帖中的说明假定你使用的是 ServiceDefaults)。
  4. Click Next > Create. 单击下一步 > 创建。

Here’s how that looks in Visual Studio 2022:
下面是在 Visual Studio 2022 中的显示效果:

Visual Studio dialog to add a service defaults project

And in Visual Studio Code, it looks like this:
在 Visual Studio 代码中,它看起来像这样:

Visual Studio Code dialog to add a service defaults project

You can also add Service Defaults from the command line by using:
您也可以使用命令行添加服务默认值:

dotnet new aspire-servicedefaults -n ServiceDefaults

All the above options just drop a new project that knows the best settings for most ASP.NET Core distributed apps into your solution. However, none of your existing apps are using it yet. We’ll hook that up next.
上述所有选项都只是将一个知道大多数 ASP.NET Core 分布式应用程序最佳设置的新项目添加到您的解决方案中。但是,您现有的应用程序都还没有使用它。接下来,我们将对其进行连接。

Configure Service Defaults

Add a reference to the ServiceDefaults project in the Api and MyWeatherHub projects:

  1. Right-click on the Api project and select Add > Reference.
  2. Check the ServiceDefaults project and click OK.
  3. Right-click on the MyWeatherHub project and select Add > Reference.
  4. Check the ServiceDefaults project and click OK.

    Visual Studio 2022 tip


    In Visual Studio 2022, you can drag and drop the project onto another project to add a reference.
  5. In both the Api and MyWeatherHub projects, update their Program.cs files, adding the following line immediately after their var builder = WebApplication.CreateBuilder(args); line:
    builder.AddServiceDefaults();
  6. In both the Api and MyWeatherHub projects, update their Program.cs files,adding the following line immediately after their var app = builder.Build(); line:
    app.MapDefaultEndpoints();

Run the application

To start with, we’re going to the application using a multiple-project launch configuration. This is fine, it’s how we’ve been doing things for years, but I have to admit I don’t really love it. Keep in mind that we’re going to make this easier in the next step. We’re doing this in two steps to make it clear what’s going on in Service Defaults and which parts are added by the AppHost.

If you’re using Visual Studio 2022, right click on the MyWeatherHub solution and go to properties. Select the Api and MyWeatherHub as startup projects, select OK.

Visual Studio dialog to set multiple startup projects

Now click Start to start and debug both projects.

If you’re using Visual Studio Code, run the Api and MyWeatherHub projects using the Run and Debug panel. The sample project already includes a launch.json file with the necessary configurations to run both.

Test the Service Defaults changes

  1. Test the application by navigating to the following URLs:
  2. You should see the Swagger UI for the API and the MyWeatherHub home page.
  3. You can also view the health checks for the API by navigating to https://localhost:7032/health.
  4. You can also view the health checks for the MyWeatherHub by navigating to https://localhost:7274/health.
  5. View the logs in the terminal to see the health checks and other telemetry data such as resiliency with Polly:
    Polly: Information: Execution attempt. Source: '-standard//Standard-Retry', Operation Key: '', Result: '200', Handled: 'False', Attempt: '0', Execution Time: '13.0649'
  6. Click on 5 different cities and a “random” error will be thrown. You will see the Polly retry policy in action.
    Polly: Warning: Execution attempt. Source: '-standard//Standard-Retry', Operation Key: '', Result: '500', Handled: 'True', Attempt: '0', Execution Time: '9732.8258'
    Polly: Warning: Resilience event occurred. EventName: 'OnRetry', Source: '-standard//Standard-Retry', Operation Key: '', Result: '500'
    System.Net.Http.HttpClient.NwsManager.ClientHandler: Information: Sending HTTP request GET http://localhost:5271/forecast/AKZ318

And that all works… the output for each application pops up in a separate console window, and we can see the health checks and logs in the terminal. So, it’s great that we’ve got all these features turned on, but it’s a bit of a pain to manage all these URLs, browser tabs, and console windows. You end up alt-tabbing between them all, and it’s a really disjointed experience.

Multiple console windows for the Api and MyWeatherHub projects

Service Defaults works great on the individual project level, but it doesn’t help us manage multiple projects in a solution. That’s where the AppHost comes in.

Step 2. Simplify launch and add a fancy dashboard with AppHost

Okay, that was pretty cool! We added a project to our solution and two lines of code, and we got health checks, logging, resiliency, and more.

But we can make that even better by adding an AppHost. That multiple-project configuration thing works, but it’s a bit annoying to set up and keep updated as we add other projects to the solution. Once we’re running we have to browse to a bunch of urls with different ports and manage each project separately. For instance, if we want to see logs or output, we have to check in each project’s console window. This gets even worse as we add more APIs and services to the solution – more URLs to manage, more console windows to check, etc. We’ve probably got some fancy dashboards and monitoring set up in production, but that doesn’t help me while I’m developing.

The AppHost has a lot of great features, but two of my favorite are the solutions to the problems above: it simplifies project launch and it adds an amazing dashboard to monitor and manage my app in my development environment. The best way to understand what it’s doing it to just add it to our solution.

Adding an AppHost project

This is the standard “add project” steps we ran through before with ServiceDefaults, but this time we’re going to pick “.NET Aspire App Host” as the project template. In Visual Studio 2022 or Visual Studio Code with the C# DevKit installed:

  1. Right-click on the solution and select Add > New Project.
  2. Select the .NET Aspire App Host project template.
  3. Name the project AppHost (again, any name would work).
  4. Click Next > Create.

Visual Studio dialog to add a app host project

Visual Studio Code dialog to add a app host project

And from the command-line, you can do that with:

dotnet new aspire-apphost -n AppHost

Just like when we added the Service Defaults, we need to add project references and a few lines of code to put the AppHost to work.

Add project references

Add a reference to the Api and MyWeatherHub projects in the new AppHost project:

  1. Right-click on the AppHost project and select Add > Reference.
  2. Check the Api and MyWeatherHub projects and click OK.

Note: Bonus points if you remembered the earlier tip that you can drag and drop the project onto another project to add a reference.

When these references are added Source Generators automatically generate the necessary code to reference the projects in the App Host.

Orchestrate the Application

In the AppHost project, update the Program.cs file, adding the following line immediately after the var builder = DistributedApplication.CreateBuilder(args); line:

 var api = builder.AddProject<Projects.Api>("api");
 var web = builder.AddProject<Projects.MyWeatherHub>("myweatherhub");

Run the application… the easy way!

Previously, we set up a multi-project launch profile. That still works, but from now on, you won’t have to bother with that. Instead, set the AppHost project as the startup project. It knows about all the other projects, and will launch them all automatically. That means that if you add an AppHost at the beginning (or use either the .NET Aspire Starter Application template or the .NET Aspire Application template), you never need to set up a multi-project launch profile again. And even better, if you add more services to your solution, the AppHost will automatically pick them up, too.

In Visual Studio, you can set the AppHost project as the startup project in Visual Studio by right clicking on the AppHost and clicking Set Default Project and hitting Start.

If you’re using Visual Studio Code, replace the contents of your launch.json file with the following and then hitting Run in the Run and Debug panel.

 {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Run AppHost",
                "type": "dotnet",
                "request": "launch",
                "projectPath": "${workspaceFolder}\\AppHost\\AppHost.csproj"
            }
        ]
    }

Hey, we’ve got a dashboard!

Remember how we had to browse to a bunch of different URLs to see our app and its health checks? Now, the AppHost will automatically launch a dashboard with all our services and their dependencies. It rolls up all the health checks, traces, logs, and information like environment variables in one place. And, if we add more services to our solution, they’ll automatically show up in the dashboard. Let’s take a look.

.NET Aspire dashboard

First, let’s take a look at the resources. This is a handy listing of all the resources in our solution. We can see the API and MyWeatherHub projects and watch their state as they start up. We also get clickable links to their endpoints, logs, and traces.

The ServiceDefaults project we added earlier automatically configures tracing for all of our projects. We can see that in the Traces tab. This is a great way to understanding timing and dependencies in our app.

.NET Aspire Dashboard showing trace view

The Metrics tab shows us a lot of information about our app, including CPU and memory usage, and the number of requests and errors. Again, this is all automatically set up for us by the ServiceDefaults project and exposed in the AppHost dashboard.

.NET Aspire Dashboard showing metrics view

The Structured tab shows us all the structured logs from our app. This is a great way to see errors and other important information in our app.

.NET Aspire Dashboard showing errors

Summary

The point is, .NET Aspire isn’t just for new apps or giant enterprise solutions. It’s for you, right now, to make your existing apps better. You can add it to your existing solutions and get a lot of benefits with just a few lines of code. And, if you’re not ready to use more advanced features like service discovery or containerized deployment, that’s okay. You can still benefit from the simplicity and reliability that .NET Aspire brings to your apps.

5 comments

Leave a comment


Newest
  • Johan Visser 0

    Thanks for the comprehensive description of Aspire.
    The more I read about Aspire, the more I think it is NOT for me.
    I only create WPF applications.
    So far I have not seen anything that makes me think that Aspire can be used in a desktop application. (WPF, WinForms, or even MAUI)

    I might be wrong, but I have just not found an...

    Read more

  • Tinh Ngo Tan 0

    Hi Jon,
    Thanks a bunch for such a great article.
    For: Configure Service Defaults => Add a reference to the ServiceDefaults project in the Api and MyWeatherHub projects:
    It should be
    3. Right-click on the Api => MyWeatherHub project and select Add > Refere...

    Read more

  • Melissa P 1 day ago 1

    The Aspire Dashboard is great, at my company we use it during development and staging… but without any k8s and docker imaging… just the plain app. It’s a single app, that either runs as a service, a standalone console app (–console) or as an aspire host (–aspire) that just pretends to be an aspire project/host and spawns itself again as the act...

    Read more

    • Jon GallowayMicrosoft employee Author 1 day ago · Edited 0

      That’s great! Exactly the thinking behind putting this blog post together – you can use individual features in .NET Aspire, like the dashboard, to simplify your dev / stage process. Great to hear it!

      If you have an existing deployment technology (like Terraform), you should of course continue to use it. While it’s technically possible to...

      Read more

Feedback usabilla icon 反馈 usabilla icon