diff --git a/src/HelloShop.ApiService/HelloShop.ApiService.csproj b/src/HelloShop.ApiService/HelloShop.ApiService.csproj
index ec25ce8..2f99c2c 100644
--- a/src/HelloShop.ApiService/HelloShop.ApiService.csproj
+++ b/src/HelloShop.ApiService/HelloShop.ApiService.csproj
@@ -8,4 +8,8 @@
+
+
+
+
\ No newline at end of file
diff --git a/src/HelloShop.ApiService/Infrastructure/ConfiguredServiceEndPoint.cs b/src/HelloShop.ApiService/Infrastructure/ConfiguredServiceEndPoint.cs
new file mode 100644
index 0000000..85bae37
--- /dev/null
+++ b/src/HelloShop.ApiService/Infrastructure/ConfiguredServiceEndPoint.cs
@@ -0,0 +1,9 @@
+namespace HelloShop.ApiService.Infrastructure
+{
+ public class ConfiguredServiceEndPoint
+ {
+ public required string ServiceName { get; set; }
+
+ public IReadOnlyCollection? Endpoints { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/src/HelloShop.ApiService/Infrastructure/ConfiguredServiceEndPointResolver.cs b/src/HelloShop.ApiService/Infrastructure/ConfiguredServiceEndPointResolver.cs
new file mode 100644
index 0000000..894b325
--- /dev/null
+++ b/src/HelloShop.ApiService/Infrastructure/ConfiguredServiceEndPointResolver.cs
@@ -0,0 +1,35 @@
+
+using Microsoft.Extensions.Options;
+using Microsoft.Extensions.ServiceDiscovery.Abstractions;
+
+namespace HelloShop.ApiService.Infrastructure;
+
+public class ConfiguredServiceEndPointResolver(IConfiguration configuration, IOptions resolverOptions) : IConfiguredServiceEndPointResolver
+{
+ private readonly Lazy> _serviceEndPoints = new(() =>
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(resolverOptions.Value.SectionName, nameof(resolverOptions.Value.SectionName));
+
+ IConfigurationSection section = configuration.GetRequiredSection(resolverOptions.Value.SectionName);
+
+ List serviceEndPoints = [];
+
+ foreach (IConfigurationSection serviceSection in section.GetChildren())
+ {
+ string serviceName = serviceSection.Key;
+
+ serviceEndPoints.Add(new ConfiguredServiceEndPoint
+ {
+ ServiceName = serviceName,
+ Endpoints = serviceSection.GetChildren().SelectMany(x => x.Get>() ?? []).Distinct().ToList()
+ });
+ }
+
+ return serviceEndPoints;
+ });
+
+ public async Task> GetConfiguredServiceEndpointsAsync(CancellationToken cancellationToken = default)
+ {
+ return await Task.FromResult(_serviceEndPoints.Value);
+ }
+}
diff --git a/src/HelloShop.ApiService/Infrastructure/CustomReverseProxyConfigProvider.cs b/src/HelloShop.ApiService/Infrastructure/CustomReverseProxyConfigProvider.cs
new file mode 100644
index 0000000..824f09c
--- /dev/null
+++ b/src/HelloShop.ApiService/Infrastructure/CustomReverseProxyConfigProvider.cs
@@ -0,0 +1,61 @@
+using Yarp.ReverseProxy.Configuration;
+using Yarp.ReverseProxy.LoadBalancing;
+
+namespace HelloShop.ApiService.Infrastructure;
+
+public class CustomReverseProxyConfigProvider(IConfiguredServiceEndPointResolver configuredServiceEndPointResolver) : IReverseProxyConfigProvider
+{
+ public async Task> GetRoutesAsync()
+ {
+ List routeConfigs = [];
+
+ foreach (var serviceEndPoint in await configuredServiceEndPointResolver.GetConfiguredServiceEndpointsAsync())
+ {
+ string serviceName = serviceEndPoint.ServiceName;
+
+ routeConfigs.Add(new RouteConfig()
+ {
+ // Forces a new route id each time GetRoutes is called.
+ RouteId = serviceName,
+ ClusterId = serviceName,
+ Match = new RouteMatch
+ {
+ // This catch-all pattern matches all request paths.
+ Path = $"{serviceEndPoint.ServiceName}/{{**remainder}}"
+ },
+ Transforms = [new Dictionary { { "PathPattern", "{**remainder}" } }]
+ });
+ }
+
+ return routeConfigs;
+ }
+
+ public async Task> GetClustersAsync()
+ {
+ List clusterConfigs = [];
+
+ foreach (var serviceEndPoint in await configuredServiceEndPointResolver.GetConfiguredServiceEndpointsAsync())
+ {
+ string serviceName = serviceEndPoint.ServiceName;
+
+ string? address = serviceEndPoint.Endpoints?.OrderBy(x => x)?.FirstOrDefault();
+
+ if (!string.IsNullOrWhiteSpace(address))
+ {
+ UriBuilder uriBuilder = new(address) { Host = serviceName };
+
+ clusterConfigs.Add(new ClusterConfig()
+ {
+ ClusterId = serviceName,
+ LoadBalancingPolicy = LoadBalancingPolicies.FirstAlphabetical,
+ Destinations = new Dictionary(StringComparer.OrdinalIgnoreCase)
+ {
+ { "destination1", new DestinationConfig() { Address = uriBuilder.ToString() } }
+ },
+ });
+ }
+ }
+
+ return clusterConfigs;
+ }
+}
diff --git a/src/HelloShop.ApiService/Infrastructure/IConfiguredServiceEndPointResolver.cs b/src/HelloShop.ApiService/Infrastructure/IConfiguredServiceEndPointResolver.cs
new file mode 100644
index 0000000..5dfdaaf
--- /dev/null
+++ b/src/HelloShop.ApiService/Infrastructure/IConfiguredServiceEndPointResolver.cs
@@ -0,0 +1,6 @@
+namespace HelloShop.ApiService.Infrastructure;
+
+public interface IConfiguredServiceEndPointResolver
+{
+ public Task> GetConfiguredServiceEndpointsAsync(CancellationToken cancellationToken = default);
+}
\ No newline at end of file
diff --git a/src/HelloShop.ApiService/Infrastructure/IReverseProxyConfigProvider.cs b/src/HelloShop.ApiService/Infrastructure/IReverseProxyConfigProvider.cs
new file mode 100644
index 0000000..f4bc04d
--- /dev/null
+++ b/src/HelloShop.ApiService/Infrastructure/IReverseProxyConfigProvider.cs
@@ -0,0 +1,10 @@
+using Yarp.ReverseProxy.Configuration;
+
+namespace HelloShop.ApiService.Infrastructure;
+
+public interface IReverseProxyConfigProvider
+{
+ Task> GetRoutesAsync();
+
+ Task> GetClustersAsync();
+}
diff --git a/src/HelloShop.ApiService/Program.cs b/src/HelloShop.ApiService/Program.cs
index 05d375d..1e3e825 100644
--- a/src/HelloShop.ApiService/Program.cs
+++ b/src/HelloShop.ApiService/Program.cs
@@ -1,39 +1,37 @@
+using HelloShop.ApiService.Infrastructure;
+using Yarp.ReverseProxy.Configuration;
+
var builder = WebApplication.CreateBuilder(args);
// Add service defaults & Aspire components.
builder.AddServiceDefaults();
// Add services to the container.
-builder.Services.AddProblemDetails();
+builder.Services.AddControllers().AddDataAnnotationsLocalization();
+
+builder.Services.AddHttpForwarderWithServiceDiscovery();
+
+builder.Services.AddReverseProxy()
+ .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
+ .LoadFromMemory(routes: [], clusters: []);
+
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
var app = builder.Build();
-// Configure the HTTP request pipeline.
-app.UseExceptionHandler();
-
-var summaries = new[]
-{
- "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
-};
-
-app.MapGet("/weatherforecast", () =>
-{
- var forecast = Enumerable.Range(1, 5).Select(index =>
- new WeatherForecast
- (
- DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
- Random.Shared.Next(-20, 55),
- summaries[Random.Shared.Next(summaries.Length)]
- ))
- .ToArray();
- return forecast;
-});
-
app.MapDefaultEndpoints();
-app.Run();
-
-record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
+app.Services.GetRequiredService().ApplicationStarted.Register(async () =>
{
- public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
-}
+ IReverseProxyConfigProvider provider = app.Services.GetRequiredService();
+ IReadOnlyList routes = await provider.GetRoutesAsync();
+ IReadOnlyList clusters = await provider.GetClustersAsync();
+ app.Services.GetRequiredService().Update(routes, clusters);
+});
+
+app.MapReverseProxy();
+
+app.MapControllers();
+
+app.Run();
diff --git a/src/HelloShop.ApiService/Properties/launchSettings.json b/src/HelloShop.ApiService/Properties/launchSettings.json
index fbac35f..aa60afc 100644
--- a/src/HelloShop.ApiService/Properties/launchSettings.json
+++ b/src/HelloShop.ApiService/Properties/launchSettings.json
@@ -5,7 +5,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
- "launchUrl": "weatherforecast",
+ "launchUrl": "swagger",
"applicationUrl": "http://localhost:5391",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
diff --git a/src/HelloShop.ApiService/appsettings.json b/src/HelloShop.ApiService/appsettings.json
index 10f68b8..624e65d 100644
--- a/src/HelloShop.ApiService/appsettings.json
+++ b/src/HelloShop.ApiService/appsettings.json
@@ -5,5 +5,29 @@
"Microsoft.AspNetCore": "Warning"
}
},
- "AllowedHosts": "*"
-}
+ "AllowedHosts": "*",
+ "ReverseProxy": {
+ "Routes": {
+ "testserviceRoute": {
+ "ClusterId": "testServiceCluster",
+ "Match": {
+ "Path": "testservice/{**remainder}"
+ },
+ "Transforms": [
+ {
+ "PathPattern": "{**remainder}"
+ }
+ ]
+ }
+ },
+ "Clusters": {
+ "testServiceCluster": {
+ "Destinations": {
+ "testServiceCluster/destination1": {
+ "Address": "http://identityservice"
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/HelloShop.AppHost/Program.cs b/src/HelloShop.AppHost/Program.cs
index 058fc9e..ac376ef 100644
--- a/src/HelloShop.AppHost/Program.cs
+++ b/src/HelloShop.AppHost/Program.cs
@@ -1,14 +1,18 @@
var builder = DistributedApplication.CreateBuilder(args);
-var apiservice = builder.AddProject("apiservice");
+var identityService = builder.AddProject("identityservice");
-builder.AddProject("identityservice");
+var orderingService=builder.AddProject("orderingservice").WithReference(identityService);
-builder.AddProject("orderingservice");
+var productService = builder.AddProject("productservice").WithReference(identityService);
-builder.AddProject("productservice");
+var basketService = builder.AddProject("basketservice").WithReference(identityService);
-builder.AddProject("basketservice");
+var apiservice = builder.AddProject("apiservice")
+.WithReference(identityService)
+.WithReference(orderingService)
+.WithReference(productService)
+.WithReference(basketService);
builder.AddProject("webapp").WithReference(apiservice);
diff --git a/src/HelloShop.ProductService/Program.cs b/src/HelloShop.ProductService/Program.cs
index 38f9161..2f1cdb2 100644
--- a/src/HelloShop.ProductService/Program.cs
+++ b/src/HelloShop.ProductService/Program.cs
@@ -22,10 +22,7 @@ builder.Services.AddCustomLocalization();
builder.Services.AddOpenApi();
builder.Services.AddModelMapper().AddModelValidator();
builder.Services.AddLocalization().AddPermissionDefinitions();
-builder.Services.AddAuthorization().AddRemotePermissionChecker(options =>
-{
- options.ApiEndpoint = "https://localhost:5001";
-}).AddCustomAuthorization();
+builder.Services.AddAuthorization().AddRemotePermissionChecker().AddCustomAuthorization();
// End addd extensions services to the container.
var app = builder.Build();
diff --git a/src/HelloShop.ServiceDefaults/Authorization/RemotePermissionChecker.cs b/src/HelloShop.ServiceDefaults/Authorization/RemotePermissionChecker.cs
index 860a177..2093a93 100644
--- a/src/HelloShop.ServiceDefaults/Authorization/RemotePermissionChecker.cs
+++ b/src/HelloShop.ServiceDefaults/Authorization/RemotePermissionChecker.cs
@@ -9,10 +9,8 @@ using System.Net.Http.Json;
namespace HelloShop.ServiceDefaults.Authorization;
-public class RemotePermissionChecker(IHttpContextAccessor httpContextAccessor, IDistributedCache distributedCache, IHttpClientFactory httpClientFactory, IOptions options) : PermissionChecker(httpContextAccessor, distributedCache)
+public class RemotePermissionChecker(IHttpContextAccessor httpContextAccessor, IDistributedCache distributedCache, IHttpClientFactory httpClientFactory) : PermissionChecker(httpContextAccessor, distributedCache)
{
- private readonly RemotePermissionCheckerOptions _remotePermissionCheckerOptions = options.Value;
-
public override async Task IsGrantedAsync(int roleId, string permissionName, string? resourceType = null, string? resourceId = null)
{
string? accessToken = await HttpContext.GetTokenAsync("access_token");
@@ -21,7 +19,7 @@ public class RemotePermissionChecker(IHttpContextAccessor httpContextAccessor, I
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
- httpClient.BaseAddress = new Uri(_remotePermissionCheckerOptions.ApiEndpoint);
+ httpClient.BaseAddress = new Uri("http://identityservice");
Dictionary parameters = new()
{
diff --git a/src/HelloShop.ServiceDefaults/Authorization/RemotePermissionCheckerOptions.cs b/src/HelloShop.ServiceDefaults/Authorization/RemotePermissionCheckerOptions.cs
deleted file mode 100644
index dd38ad4..0000000
--- a/src/HelloShop.ServiceDefaults/Authorization/RemotePermissionCheckerOptions.cs
+++ /dev/null
@@ -1,6 +0,0 @@
-namespace HelloShop.ServiceDefaults.Authorization;
-
-public class RemotePermissionCheckerOptions
-{
- public string ApiEndpoint { get; set; } = default!;
-}
diff --git a/src/HelloShop.ServiceDefaults/Extensions/PermissionExtensions.cs b/src/HelloShop.ServiceDefaults/Extensions/PermissionExtensions.cs
index 62f6e9d..befc61a 100644
--- a/src/HelloShop.ServiceDefaults/Extensions/PermissionExtensions.cs
+++ b/src/HelloShop.ServiceDefaults/Extensions/PermissionExtensions.cs
@@ -65,10 +65,8 @@ public static class PermissionExtensions
return routeGroup;
}
- public static IServiceCollection AddRemotePermissionChecker(this IServiceCollection services, Action configureOptions)
+ public static IServiceCollection AddRemotePermissionChecker(this IServiceCollection services)
{
- services.Configure(configureOptions);
-
services.AddTransient();
return services;