Skip to content

Commit

Permalink
Merge pull request #10 from unrealbg/dev
Browse files Browse the repository at this point in the history
Revamp Project Structure with Aspire.AppHost.Sdk and Enhance API Testing
  • Loading branch information
unrealbg authored Jan 4, 2025
2 parents 15e0efc + 5d530c6 commit c3f3004
Show file tree
Hide file tree
Showing 13 changed files with 247 additions and 7 deletions.
23 changes: 23 additions & 0 deletions BlazorShop.AppHost/BlazorShop.AppHost.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">

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

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireHost>true</IsAspireHost>
<UserSecretsId>d3573504-3570-47c0-8129-3287c9a91907</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\BlazorShop.Presentation\BlazorShop.API\BlazorShop.API.csproj" />
<ProjectReference Include="..\BlazorShop.Presentation\BlazorShop.Web\BlazorShop.Web.csproj" />
</ItemGroup>

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

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

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

builder.Build().Run();
29 changes: 29 additions & 0 deletions BlazorShop.AppHost/Properties/launchSettings.json
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:17025;http://localhost:15164",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21239",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22065"
}
},
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:15164",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19204",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20124"
}
}
}
}
8 changes: 8 additions & 0 deletions BlazorShop.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 BlazorShop.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"
}
}
}
2 changes: 1 addition & 1 deletion BlazorShop.Application/Services/ProductService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public async Task<IEnumerable<GetProduct>> GetAllAsync()
public async Task<GetProduct> GetByIdAsync(Guid id)
{
var result = await _productRepository.GetByIdAsync(id);
return result != null ? _mapper.Map<GetProduct>(result) : new GetProduct();
return result != null ? _mapper.Map<GetProduct>(result) : null;
}

public async Task<ServiceResponse> AddAsync(CreateProduct product)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

<ItemGroup>
<ProjectReference Include="..\..\BlazorShop.Infrastructure\BlazorShop.Infrastructure.csproj" />
<ProjectReference Include="..\..\BlazorShop.ServiceDefaults\BlazorShop.ServiceDefaults.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
8 changes: 7 additions & 1 deletion BlazorShop.Presentation/BlazorShop.API/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace BlazorShop.API
using BlazorShop.Infrastructure;

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;

using Serilog;

Expand All @@ -30,6 +31,8 @@ public static void Main(string[] args)
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddSwaggerGen();

builder.AddServiceDefaults();

builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddApplication();
builder.Services.AddCors(
Expand All @@ -41,7 +44,10 @@ public static void Main(string[] args)
opt.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins("https://localhost:7258");
//.WithOrigins("https://localhost:7258");
.SetIsOriginAllowed(origin =>
origin.StartsWith("http://localhost") ||
origin.StartsWith("https://localhost"));
});
});

Expand Down
22 changes: 22 additions & 0 deletions BlazorShop.ServiceDefaults/BlazorShop.ServiceDefaults.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net9.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="9.0.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.0.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
</ItemGroup>

</Project>
119 changes: 119 additions & 0 deletions BlazorShop.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 Microsoft.Extensions.ServiceDiscovery;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

namespace Microsoft.Extensions.Hosting;

// Adds common .NET Aspire services: service discovery, resilience, health checks, and OpenTelemetry.
// This project should be referenced by each service project in your solution.
// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults
public static class Extensions
{
public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
{
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.AddServiceDiscovery();
});

// Uncomment the following to restrict the allowed schemes for service discovery.
// builder.Services.Configure<ServiceDiscoveryOptions>(options =>
// {
// options.AllowedSchemes = ["https"];
// });

return builder;
}

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

builder.Services.AddOpenTelemetry()
.WithMetrics(metrics =>
{
metrics.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddRuntimeInstrumentation();
})
.WithTracing(tracing =>
{
tracing.AddSource(builder.Environment.ApplicationName)
.AddAspNetCoreInstrumentation()
// Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)
//.AddGrpcClientInstrumentation()
.AddHttpClientInstrumentation();
});

builder.AddOpenTelemetryExporters();

return builder;
}

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

if (useOtlpExporter)
{
builder.Services.AddOpenTelemetry().UseOtlpExporter();
}

// Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)
//if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]))
//{
// builder.Services.AddOpenTelemetry()
// .UseAzureMonitor();
//}

return builder;
}

public static TBuilder AddDefaultHealthChecks<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
{
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)
{
// Adding health checks endpoints to applications in non-development environments has security implications.
// See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments.
if (app.Environment.IsDevelopment())
{
// 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;
}
}
9 changes: 4 additions & 5 deletions BlazorShop.Tests/Application/Services/ProductServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,24 +105,23 @@ public async Task GetByIdAsync_WhenProductExists_ShouldReturnMappedProduct()
}

[Fact]
public async Task GetByIdAsync_WhenProductDoesNotExist_ShouldReturnEmptyProduct()
public async Task GetByIdAsync_WhenProductDoesNotExist_ShouldReturnNull()
{
// Arrange
var productId = Guid.NewGuid();
this._mockProductRepository.Setup(repo => repo.GetByIdAsync(productId))
.ReturnsAsync((Product)null);
.ReturnsAsync((Product)null);

// Act
var result = await this._productService.GetByIdAsync(productId);

// Assert
Assert.NotNull(result);
Assert.Equal(default, result.Id);
Assert.Null(result.Name);
Assert.Null(result);
this._mockProductRepository.Verify(repo => repo.GetByIdAsync(productId), Times.Once);
this._mockMapper.Verify(mapper => mapper.Map<GetProduct>(It.IsAny<Product>()), Times.Never);
}


[Fact]
public async Task AddAsync_WhenProductIsAdded_ShouldReturnSuccessResponse()
{
Expand Down
2 changes: 2 additions & 0 deletions BlazorShop.Tests/BlazorShop.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.Testing" Version="9.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="xunit" Version="2.9.2" />
Expand All @@ -24,6 +25,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\BlazorShop.AppHost\BlazorShop.AppHost.csproj" />
<ProjectReference Include="..\BlazorShop.Application\BlazorShop.Application.csproj" />
<ProjectReference Include="..\BlazorShop.Presentation\BlazorShop.Web.Shared\BlazorShop.Web.Shared.csproj" />
</ItemGroup>
Expand Down
12 changes: 12 additions & 0 deletions BlazorShop.sln
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlazorShop.Web.Shared", "Bl
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlazorShop.Tests", "BlazorShop.Tests\BlazorShop.Tests.csproj", "{FECE84AC-01C9-4F82-9EDA-DD56713E574A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlazorShop.AppHost", "BlazorShop.AppHost\BlazorShop.AppHost.csproj", "{3239FA28-A508-4EEC-9351-89E414E7B816}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlazorShop.ServiceDefaults", "BlazorShop.ServiceDefaults\BlazorShop.ServiceDefaults.csproj", "{CB802A92-ED5C-732A-C9BD-5887C0D03E13}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -53,6 +57,14 @@ Global
{FECE84AC-01C9-4F82-9EDA-DD56713E574A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FECE84AC-01C9-4F82-9EDA-DD56713E574A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FECE84AC-01C9-4F82-9EDA-DD56713E574A}.Release|Any CPU.Build.0 = Release|Any CPU
{3239FA28-A508-4EEC-9351-89E414E7B816}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3239FA28-A508-4EEC-9351-89E414E7B816}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3239FA28-A508-4EEC-9351-89E414E7B816}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3239FA28-A508-4EEC-9351-89E414E7B816}.Release|Any CPU.Build.0 = Release|Any CPU
{CB802A92-ED5C-732A-C9BD-5887C0D03E13}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CB802A92-ED5C-732A-C9BD-5887C0D03E13}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CB802A92-ED5C-732A-C9BD-5887C0D03E13}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CB802A92-ED5C-732A-C9BD-5887C0D03E13}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down

0 comments on commit c3f3004

Please sign in to comment.