Skip to content

Commit

Permalink
add .NET Aspire
Browse files Browse the repository at this point in the history
  • Loading branch information
phmatray committed Mar 14, 2024
1 parent 9ae265b commit d604952
Show file tree
Hide file tree
Showing 19 changed files with 351 additions and 118,610 deletions.
25 changes: 25 additions & 0 deletions geometrix-api/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/.idea
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
2 changes: 2 additions & 0 deletions geometrix-api/.idea/.idea.Geometrix/.idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions geometrix-api/Geometrix.AppHost/Geometrix.AppHost.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireHost>true</IsAspireHost>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting" Version="8.0.0-preview.3.24105.21"/>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Geometrix.WebApi\Geometrix.WebApi.csproj" />
</ItemGroup>

</Project>
5 changes: 5 additions & 0 deletions geometrix-api/Geometrix.AppHost/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
var builder = DistributedApplication.CreateBuilder(args);

builder.AddProject<Projects.Geometrix_WebApi>("Geometrix.WebApi");

builder.Build().Run();
16 changes: 16 additions & 0 deletions geometrix-api/Geometrix.AppHost/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:15238",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:16209"
}
}
}
}
8 changes: 8 additions & 0 deletions geometrix-api/Geometrix.AppHost/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions geometrix-api/Geometrix.AppHost/appsettings.json
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"
}
}
}
30 changes: 30 additions & 0 deletions geometrix-api/Geometrix.Backend/Geometrix.Backend.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.0.0
MinimumVisualStudioVersion = 17.8.0.0
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Geometrix.Backend.AppHost", "Geometrix.Backend.AppHost\Geometrix.Backend.AppHost.csproj", "{7AB3E48D-FDE9-4C23-8F58-810E1374C60F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Geometrix.Backend.ServiceDefaults", "Geometrix.Backend.ServiceDefaults\Geometrix.Backend.ServiceDefaults.csproj", "{5B07E5DC-0B17-4726-A629-3BDDD6B20907}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7AB3E48D-FDE9-4C23-8F58-810E1374C60F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7AB3E48D-FDE9-4C23-8F58-810E1374C60F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7AB3E48D-FDE9-4C23-8F58-810E1374C60F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7AB3E48D-FDE9-4C23-8F58-810E1374C60F}.Release|Any CPU.Build.0 = Release|Any CPU
{5B07E5DC-0B17-4726-A629-3BDDD6B20907}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5B07E5DC-0B17-4726-A629-3BDDD6B20907}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5B07E5DC-0B17-4726-A629-3BDDD6B20907}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5B07E5DC-0B17-4726-A629-3BDDD6B20907}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {30F9AEE8-BE5B-4F59-97A1-DE147F9BA3E6}
EndGlobalSection
EndGlobal
119 changes: 119 additions & 0 deletions geometrix-api/Geometrix.ServiceDefaults/Extensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

namespace Microsoft.Extensions.Hosting;

public static class Extensions
{
public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder)
{
builder.ConfigureOpenTelemetry();

builder.AddDefaultHealthChecks();

builder.Services.AddServiceDiscovery();

builder.Services.ConfigureHttpClientDefaults(http =>
{
// Turn on resilience by default
http.AddStandardResilienceHandler();

// Turn on service discovery by default
http.UseServiceDiscovery();
});

return builder;
}

public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicationBuilder builder)
{
builder.Logging.AddOpenTelemetry(logging =>
{
logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true;
});

builder.Services.AddOpenTelemetry()
.WithMetrics(metrics =>
{
metrics.AddRuntimeInstrumentation()
.AddBuiltInMeters();
})
.WithTracing(tracing =>
{
if (builder.Environment.IsDevelopment())
{
// We want to view all traces in development
tracing.SetSampler(new AlwaysOnSampler());
}

tracing.AddAspNetCoreInstrumentation()
.AddGrpcClientInstrumentation()
.AddHttpClientInstrumentation();
});

builder.AddOpenTelemetryExporters();

return builder;
}

private static IHostApplicationBuilder AddOpenTelemetryExporters(this IHostApplicationBuilder builder)
{
var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);

if (useOtlpExporter)
{
builder.Services.Configure<OpenTelemetryLoggerOptions>(logging => logging.AddOtlpExporter());
builder.Services.ConfigureOpenTelemetryMeterProvider(metrics => metrics.AddOtlpExporter());
builder.Services.ConfigureOpenTelemetryTracerProvider(tracing => tracing.AddOtlpExporter());
}

// Uncomment the following lines to enable the Prometheus exporter (requires the OpenTelemetry.Exporter.Prometheus.AspNetCore package)
// builder.Services.AddOpenTelemetry()
// .WithMetrics(metrics => metrics.AddPrometheusExporter());

// Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)
// builder.Services.AddOpenTelemetry()
// .UseAzureMonitor();

return builder;
}

public static IHostApplicationBuilder AddDefaultHealthChecks(this IHostApplicationBuilder builder)
{
builder.Services.AddHealthChecks()
// Add a default liveness check to ensure app is responsive
.AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);

return builder;
}

public static WebApplication MapDefaultEndpoints(this WebApplication app)
{
// Uncomment the following line to enable the Prometheus endpoint (requires the OpenTelemetry.Exporter.Prometheus.AspNetCore package)
// app.MapPrometheusScrapingEndpoint();

// All health checks must pass for app to be considered ready to accept traffic after starting
app.MapHealthChecks("/health");

// Only health checks tagged with the "live" tag must pass for app to be considered alive
app.MapHealthChecks("/alive", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("live")
});

return app;
}

private static MeterProviderBuilder AddBuiltInMeters(this MeterProviderBuilder meterProviderBuilder) =>
meterProviderBuilder.AddMeter(
"Microsoft.AspNetCore.Hosting",
"Microsoft.AspNetCore.Server.Kestrel",
"System.Net.Http");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireSharedProject>true</IsAspireSharedProject>
</PropertyGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App"/>

<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="8.1.0"/>
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="8.0.0-preview.3.24105.21"/>
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.7.0-alpha.1"/>
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.7.0-alpha.1"/>
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.6.0-beta.2"/>
<PackageReference Include="OpenTelemetry.Instrumentation.GrpcNetClient" Version="1.6.0-beta.2"/>
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.6.0-beta.2"/>
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.5.1"/>
</ItemGroup>

</Project>
1 change: 1 addition & 0 deletions geometrix-api/Geometrix.WebApi/Geometrix.WebApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
<!-- Local -->
<ProjectReference Include="..\Geometrix.Application\Geometrix.Application.csproj" />
<ProjectReference Include="..\Geometrix.Infrastructure\Geometrix.Infrastructure.csproj" />
<ProjectReference Include="..\Geometrix.ServiceDefaults\Geometrix.ServiceDefaults.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static IServiceCollection AddInvalidRequestLogging(this IServiceCollectio
var logger = actionContext
.HttpContext
.RequestServices
.GetRequiredService<ILogger<Startup>>();
.GetRequiredService<ILogger<Program>>();

var errors = actionContext.ModelState
.Values
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ private static string XmlCommentsFilePath
get
{
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var fileName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name + ".xml";
var fileName = typeof(Program).GetTypeInfo().Assembly.GetName().Name + ".xml";
return Path.Combine(basePath, fileName);
}
}
Expand Down
79 changes: 61 additions & 18 deletions geometrix-api/Geometrix.WebApi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,64 @@
namespace Geometrix.WebApi;
using Geometrix.WebApi.Modules;
using Geometrix.WebApi.Modules.Common;
using Geometrix.WebApi.Modules.Common.FeatureFlags;
using Geometrix.WebApi.Modules.Common.Swagger;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Prometheus;

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
var services = builder.Services;
var env = builder.Environment;

/// <summary>
/// </summary>
public static class Program
// Add Aspire services.
builder.AddServiceDefaults();

// Add other services.
services
.AddFeatureFlags(configuration) // should be the first one.
.AddInvalidRequestLogging()
.AddHealthChecks(configuration)
.AddAuthentication(configuration)
.AddVersioning()
.AddSwagger()
.AddUseCases()
.AddCustomControllers()
.AddCustomCors()
.AddProxy()
.AddCustomDataProtection();

var servicesCount = services.Count;
Console.WriteLine($"Total services registered: {servicesCount}");

var app = builder.Build();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
/// <summary>
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
=> CreateHostBuilder(args).Build().Run();

private static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((_, configApp) => { configApp.AddCommandLine(args); })
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}
app.UseExceptionHandler("/api/V1/CustomError")
.UseHsts();
}

var provider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();

app
.UseStaticFiles()
.UseProxy(configuration)
.UseHealthChecks()
.UseCustomCors()
.UseCustomHttpMetrics()
.UseRouting()
.UseVersionedSwagger(provider, configuration)
.UseAuthentication()
.UseAuthorization()
.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapMetrics();
});


app.Run();
Loading

0 comments on commit d604952

Please sign in to comment.