Skip to content

Commit

Permalink
Eventing API content, getting closer
Browse files Browse the repository at this point in the history
  • Loading branch information
IEvangelist committed Oct 24, 2024
1 parent ddf62a1 commit a73f680
Show file tree
Hide file tree
Showing 11 changed files with 163 additions and 7 deletions.
30 changes: 26 additions & 4 deletions docs/app-host/eventing.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ All of the preceding events are analogous to the [app host life cycles](xref:dot

### Subscribe to app host events

To subscribe to the built-in app host events, use the eventing API. After you have a distributed application builder instance, walk up to the <xref:Aspire.Hosting.IDistributedApplicationBuilder.Eventing?displayProperty=nameWithType> property and call the <xref:Aspire.Hosting.Eventing.IDistributedApplicationEventing.Subscribe*?displayProperty=nameWithType> API. Consider the following sample app host _Program.cs_ file:
To subscribe to the built-in app host events, use the eventing API. After you have a distributed application builder instance, walk up to the <xref:Aspire.Hosting.IDistributedApplicationBuilder.Eventing?displayProperty=nameWithType> property and call the <xref:Aspire.Hosting.Eventing.IDistributedApplicationEventing.Subscribe``1(System.Func{``0,System.Threading.CancellationToken,System.Threading.Tasks.Task})> API. Consider the following sample app host _Program.cs_ file:

:::code source="snippets/AspireApp/AspireApp.AppHost/Program.cs":::

Expand All @@ -36,11 +36,33 @@ The log output confirms that event handlers are executed in the order of the app

## Resource eventing

In addition to the app host events, you can also subscribe to resource events. Resource events are raised when a resource is created, updated, or deleted. The following events are available:
In addition to the app host events, you can also subscribe to resource events. Resource events are raised specific to an individual resource. Resource events are defined as implementations of the <xref:Aspire.Hosting.Eventing.IDistributedApplicationResourceEvent> interface. The following resource events are available in the listed order:

<xref:Aspire.Hosting.Eventing.IDistributedApplicationResourceEvent>
1. `ConnectionStringAvailableEvent`: This event is raised when a connection string becomes available for a resource.
1. <xref:Aspire.Hosting.ApplicationModel.BeforeResourceStartedEvent>: This event is raised by orchestrators before they have started a new resource.

## Event dispatch behavior
### Subscribe to resource events

To subscribe to resource events, use the eventing API. After you have a distributed application builder instance, walk up to the <xref:Aspire.Hosting.IDistributedApplicationBuilder.Eventing?displayProperty=nameWithType> property and call the <xref:Aspire.Hosting.Eventing.IDistributedApplicationEventing.Subscribe``1(Aspire.Hosting.ApplicationModel.IResource,System.Func{``0,System.Threading.CancellationToken,System.Threading.Tasks.Task})> API. Consider the following sample app host _Program.cs_ file:

:::code source="snippets/AspireApp/AspireApp.ResourceAppHost/Program.cs":::

The preceding code subscribes to the `ConnectionStringAvailableEvent` and `BeforeResourceStartedEvent` events on the `cache` resource. When <xref:Aspire.Hosting.RedisBuilderExtensions.AddRedis*> is called, it returns an <xref:Aspire.Hosting.ApplicationModel.IResourceBuilder`1> where `T` is a <xref:Aspire.Hosting.ApplicationModel.RedisResource>. The resource builder exposes the resource as the <xref:Aspire.Hosting.ApplicationModel.IResourceBuilder`1.Resource?displayProperty=nameWithType> property. This resource is then passed to the `Subscribe` API to subscribe to the events on the resource.

When the app host is run, by the time the .NET Aspire dashboard is displayed, you should see the following log output in the console:

:::code language="Output" source="snippets/AspireApp/AspireApp.ResourceAppHost/Console.txt" highlight="8,10":::

## Publish events

When subscribing to any of the built-in events, you don't need to publish the event yourself as the app host orchestrator does this for you. However, you can publish custom events with the eventing API. To publish an event, you have to first define an event as an implementation of either the <xref:Aspire.Hosting.Eventing.IDistributedApplicationEvent> or <xref:Aspire.Hosting.Eventing.IDistributedApplicationResourceEvent> interface. You need to determine which interface to implement based on whether the event is a global app host event or a resource-specific event.

Then, you can subscribe and publish the event by calling the either of the following APIs:

- <xref:Aspire.Hosting.Eventing.IDistributedApplicationEventing.PublishAsync``1(``0,System.Threading.CancellationToken)>: Publishes an event to all subscribes of the specific event type.
- `PublishAsync<T>(T @event, EventDispatchBehavior, CancellationToken)`: Publishes an event to all subscribes of the specific event type with a specified dispatch behavior.

### Event dispatch behavior

When events are dispatched, you can control how the events are dispatched to subscribers. The event dispatch behavior is controlled by the `EventDispatchBehavior` enum. The following behaviors are available:

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<Sdk Name="Aspire.AppHost.Sdk" Version="9.0.0-rc.1.24511.1" />

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireHost>true</IsAspireHost>
<UserSecretsId>7b352f08-305b-4032-9a21-90deb02efc04</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\AspireApp.ApiService\AspireApp.ApiService.csproj" />
<ProjectReference Include="..\AspireApp.Web\AspireApp.Web.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.0.0-rc.1.24511.1" />
<PackageReference Include="Aspire.Hosting.Redis" Version="9.0.0-rc.1.24511.1" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
info: Aspire.Hosting.DistributedApplication[0]
Aspire version: 9.0.0
info: Aspire.Hosting.DistributedApplication[0]
Distributed application starting.
info: Aspire.Hosting.DistributedApplication[0]
Application host directory is: ..\AspireApp\AspireApp.AppHost
info: Program[0]
1. ConnectionStringAvailableEvent
info: Program[0]
2. BeforeResourceStartedEvent
info: Aspire.Hosting.DistributedApplication[0]
Now listening on: https://localhost:17222
info: Aspire.Hosting.DistributedApplication[0]
Login to the dashboard at https://localhost:17222/login?t=<YOUR_TOKEN>
info: Aspire.Hosting.DistributedApplication[0]
Distributed application started. Press Ctrl+C to shut down.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddRedis("cache");

_ = builder.Eventing.Subscribe<BeforeResourceStartedEvent>(
cache.Resource,
static (@event, cancellationToken) =>
{
var logger = @event.Services.GetRequiredService<ILogger<Program>>();

logger.LogInformation("2. BeforeResourceStartedEvent");

return Task.CompletedTask;
});

_ = builder.Eventing.Subscribe<ConnectionStringAvailableEvent>(
cache.Resource,
static (@event, cancellationToken) =>
{
var logger = @event.Services.GetRequiredService<ILogger<Program>>();

logger.LogInformation("1. ConnectionStringAvailableEvent");

return Task.CompletedTask;
});

var apiService = builder.AddProject<Projects.AspireApp_ApiService>("apiservice");

builder.AddProject<Projects.AspireApp_Web>("webfrontend")
.WithExternalHttpEndpoints()
.WithReference(cache)
.WaitFor(cache)
.WithReference(apiService)
.WaitFor(apiService);

builder.Build().Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:17222;http://localhost:15197",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21272",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22185"
}
},
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:15197",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19149",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20298"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Aspire.Hosting.Dcp": "Warning"
}
}
}
6 changes: 6 additions & 0 deletions docs/app-host/snippets/AspireApp/AspireApp.sln
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspireApp.ApiService", "Asp
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspireApp.Web", "AspireApp.Web\AspireApp.Web.csproj", "{BA90311C-3BC4-4DBF-A81C-579540E1E9BB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspireApp.ResourceAppHost", "AspireApp.ResourceAppHost\AspireApp.ResourceAppHost.csproj", "{18D34F46-A181-4E0F-8AAF-408C16EA4C39}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -32,6 +34,10 @@ Global
{BA90311C-3BC4-4DBF-A81C-579540E1E9BB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BA90311C-3BC4-4DBF-A81C-579540E1E9BB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BA90311C-3BC4-4DBF-A81C-579540E1E9BB}.Release|Any CPU.Build.0 = Release|Any CPU
{18D34F46-A181-4E0F-8AAF-408C16EA4C39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{18D34F46-A181-4E0F-8AAF-408C16EA4C39}.Debug|Any CPU.Build.0 = Debug|Any CPU
{18D34F46-A181-4E0F-8AAF-408C16EA4C39}.Release|Any CPU.ActiveCfg = Release|Any CPU
{18D34F46-A181-4E0F-8AAF-408C16EA4C39}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
4 changes: 2 additions & 2 deletions docs/get-started/aspire-overview.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: .NET Aspire overview
description: Learn about .NET Aspire, an application stack designed to improve the experience of building cloud-native applications.
ms.date: 09/27/2024
ms.date: 10/24/2024
---

# .NET Aspire overview
Expand All @@ -14,7 +14,7 @@ ms.date: 09/27/2024
:::column-end:::
:::column span="3":::

.NET Aspire is an opinionated, cloud ready stack for building observable, production ready, distributed applications.​ .NET Aspire is delivered through a collection of NuGet packages that handle specific cloud-native concerns. Cloud-native apps often consist of small, interconnected pieces or microservices rather than a single, monolithic code base. Cloud-native apps generally consume a large number of services, such as databases, messaging, and caching.
.NET Aspire is an opinionated, cloud ready stack for building observable, production ready, distributed applications.​ .NET Aspire is delivered through a collection of NuGet packages that handle specific cloud-native concerns. Cloud-native apps often consist of small, interconnected pieces or microservices rather than a single, monolithic code base. Cloud-native apps generally consume a large number of services, such as databases, messaging, and caching. For information on support, see the [.NET Aspire Support Policy](https://dotnet.microsoft.com/platform/support/policy/aspire).

:::column-end:::
:::row-end:::
Expand Down
2 changes: 1 addition & 1 deletion docs/index.yml
Original file line number Diff line number Diff line change
Expand Up @@ -368,4 +368,4 @@ additionalContent:
summary: API reference documentation for ASP.NET Core
url: /dotnet/api?view=aspnetcore-8.0&preserve-view=true

footer: "Are you interested in contributing to the .NET Aspire docs? For more information, see our [contributor guide](/contribute/dotnet/dotnet-contribute)."
footer: "Are you interested in contributing to the .NET Aspire docs? For more information, see our [contributor guide](/contribute/dotnet/dotnet-contribute). Interested in the official support policy, see [.NET Aspire Support Policy](https://dotnet.microsoft.com/platform/support/policy/aspire)."
3 changes: 3 additions & 0 deletions docs/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -359,3 +359,6 @@ items:
href: https://github.com/dotnet/extensions
- name: ASP.NET Core
href: https://github.com/dotnet/aspnetcore

- name: Official support policy
href: https://dotnet.microsoft.com/platform/support/policy/aspire

0 comments on commit a73f680

Please sign in to comment.