Browse Source

Make the payment API use the common code

davidfowl/common-services
David Fowler 1 year ago
committed by Reuben Bond
parent
commit
57d9baf106
5 changed files with 32 additions and 196 deletions
  1. +5
    -19
      src/Services/Payment/Payment.API/GlobalUsings.cs
  2. +1
    -20
      src/Services/Payment/Payment.API/Payment.API.csproj
  3. +9
    -145
      src/Services/Payment/Payment.API/Program.cs
  4. +14
    -7
      src/Services/Payment/Payment.API/appsettings.json
  5. +3
    -5
      src/Services/Services.Common/CommonExtensions.cs

+ 5
- 19
src/Services/Payment/Payment.API/GlobalUsings.cs View File

@ -1,25 +1,11 @@
global using Azure.Core;
global using Azure.Identity;
global using HealthChecks.UI.Client;
global using Microsoft.AspNetCore.Diagnostics.HealthChecks;
global using System.Threading.Tasks;
global using Microsoft.AspNetCore.Builder;
global using Microsoft.AspNetCore;
global using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
global using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
global using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
global using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ;
global using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus;
global using Microsoft.eShopOnContainers.Payment.API;
global using Microsoft.eShopOnContainers.Payment.API.IntegrationEvents.EventHandling;
global using Microsoft.eShopOnContainers.Payment.API.IntegrationEvents.Events;
global using Microsoft.Extensions.Diagnostics.HealthChecks;
global using Microsoft.Extensions.Options;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Logging;
global using Microsoft.eShopOnContainers.Payment.API.IntegrationEvents.EventHandling;
global using Microsoft.eShopOnContainers.Payment.API;
global using RabbitMQ.Client;
global using System.Threading.Tasks;
global using System;
global using System.IO;
global using Microsoft.AspNetCore.Hosting;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Options;
global using Services.Common;

+ 1
- 20
src/Services/Payment/Payment.API/Payment.API.csproj View File

@ -3,29 +3,10 @@
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<DockerComposeProjectPath>..\..\..\..\docker-compose.dcproj</DockerComposeProjectPath>
<AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81;</AssetTargetFallback>
<GenerateErrorForMissingTargetingPacks>false</GenerateErrorForMissingTargetingPacks>
<IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AspNetCore.HealthChecks.AzureServiceBus" />
<PackageReference Include="AspNetCore.HealthChecks.Rabbitmq" />
<PackageReference Include="AspNetCore.HealthChecks.UI.Client" />
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" />
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" />
<PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" />
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBusRabbitMQ\EventBusRabbitMQ.csproj" />
<ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBusServiceBus\EventBusServiceBus.csproj" />
<ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBus\EventBus.csproj" />
<ProjectReference Include="..\..\..\BuildingBlocks\EventBus\IntegrationEventLogEF\IntegrationEventLogEF.csproj" />
<ProjectReference Include="..\..\Services.Common\Services.Common.csproj" />
</ItemGroup>
</Project>

+ 9
- 145
src/Services/Payment/Payment.API/Program.cs View File

@ -1,158 +1,22 @@
var builder = WebApplication.CreateBuilder(args);
if (builder.Configuration.GetValue<bool>("UseVault", false))
{
TokenCredential credential = new ClientSecretCredential(
builder.Configuration["Vault:TenantId"],
builder.Configuration["Vault:ClientId"],
builder.Configuration["Vault:ClientSecret"]);
builder.Configuration.AddAzureKeyVault(new Uri($"https://{builder.Configuration["Vault:Name"]}.vault.azure.net/"), credential);
}
builder.Configuration.SetBasePath(Directory.GetCurrentDirectory());
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
builder.Configuration.AddEnvironmentVariables();
builder.WebHost.CaptureStartupErrors(false);
builder.Services
.AddCustomHealthCheck(builder.Configuration);
builder.Services.Configure<PaymentSettings>(builder.Configuration);
builder.Services.AddApplicationInsightsTelemetry(builder.Configuration);
if (builder.Configuration.GetValue<bool>("AzureServiceBusEnabled"))
{
builder.Services.AddSingleton<IServiceBusPersisterConnection>(sp =>
{
var serviceBusConnectionString = builder.Configuration["EventBusConnection"];
var subscriptionClientName = builder.Configuration["SubscriptionClientName"];
return new DefaultServiceBusPersisterConnection(serviceBusConnectionString);
});
}
else
{
builder.Services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
{
var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
var factory = new ConnectionFactory()
{
HostName = builder.Configuration["EventBusConnection"],
DispatchConsumersAsync = true
};
builder.AddServiceDefaults();
if (!string.IsNullOrEmpty(builder.Configuration["EventBusUserName"]))
{
factory.UserName = builder.Configuration["EventBusUserName"];
}
if (!string.IsNullOrEmpty(builder.Configuration["EventBusPassword"]))
{
factory.Password = builder.Configuration["EventBusPassword"];
}
builder.Services.Configure<PaymentSettings>(builder.Configuration);
var retryCount = 5;
if (!string.IsNullOrEmpty(builder.Configuration["EventBusRetryCount"]))
{
retryCount = int.Parse(builder.Configuration["EventBusRetryCount"]);
}
builder.Services.AddTransient<OrderStatusChangedToStockConfirmedIntegrationEventHandler>();
return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
});
}
RegisterEventBus(builder.Services);
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
var pathBase = app.Configuration["PATH_BASE"];
if (!string.IsNullOrEmpty(pathBase))
{
app.UsePathBase(pathBase);
}
ConfigureEventBus(app);
app.UseRouting();
app.MapHealthChecks("/hc", new HealthCheckOptions()
if (!await app.CheckHealthAsync())
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
app.MapHealthChecks("/liveness", new HealthCheckOptions
{
Predicate = r => r.Name.Contains("self")
});
await app.RunAsync();
void RegisterEventBus(IServiceCollection services)
{
if (builder.Configuration.GetValue<bool>("AzureServiceBusEnabled"))
{
services.AddSingleton<IEventBus, EventBusServiceBus>(sp =>
{
var serviceBusPersisterConnection = sp.GetRequiredService<IServiceBusPersisterConnection>();
var logger = sp.GetRequiredService<ILogger<EventBusServiceBus>>();
var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
string subscriptionName = builder.Configuration["SubscriptionClientName"];
return new EventBusServiceBus(serviceBusPersisterConnection, logger,
eventBusSubcriptionsManager, sp, subscriptionName);
});
}
else
{
services.AddSingleton<IEventBus, EventBusRabbitMQ>(sp =>
{
var subscriptionClientName = builder.Configuration["SubscriptionClientName"];
var rabbitMQPersistentConnection = sp.GetRequiredService<IRabbitMQPersistentConnection>();
var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>();
var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
var retryCount = 5;
if (!string.IsNullOrEmpty(builder.Configuration["EventBusRetryCount"]))
{
retryCount = int.Parse(builder.Configuration["EventBusRetryCount"]);
}
return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, sp, eventBusSubcriptionsManager, subscriptionClientName, retryCount);
});
}
services.AddTransient<OrderStatusChangedToStockConfirmedIntegrationEventHandler>();
services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
return;
}
void ConfigureEventBus(IApplicationBuilder app)
{
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<OrderStatusChangedToStockConfirmedIntegrationEvent, OrderStatusChangedToStockConfirmedIntegrationEventHandler>();
}
app.UseServiceDefaults();
public static class CustomExtensionMethods
{
public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration)
{
var hcBuilder = services.AddHealthChecks();
var eventBus = app.Services.GetRequiredService<IEventBus>();
hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy());
eventBus.Subscribe<OrderStatusChangedToStockConfirmedIntegrationEvent, OrderStatusChangedToStockConfirmedIntegrationEventHandler>();
if (configuration.GetValue<bool>("AzureServiceBusEnabled"))
{
hcBuilder
.AddAzureServiceBusTopic(
configuration["EventBusConnection"],
topicName: "eshop_event_bus",
name: "payment-servicebus-check",
tags: new string[] { "servicebus" });
}
else
{
hcBuilder
.AddRabbitMQ(
$"amqp://{configuration["EventBusConnection"]}",
name: "payment-rabbitmqbus-check",
tags: new string[] { "rabbitmqbus" });
}
return services;
}
}
await app.RunAsync();

+ 14
- 7
src/Services/Payment/Payment.API/appsettings.json View File

@ -1,9 +1,16 @@
{
"PaymentSucceeded": true,
"AzureServiceBusEnabled": false,
"SubscriptionClientName": "Payment",
"ApplicationInsights": {
"InstrumentationKey": ""
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"EventBusRetryCount": 5
}
"ConnectionStrings": {
"EventBus": "localhost"
},
"EventBus": {
"SubscriptionClientName": "Payment",
"RetryCount": 5
},
"PaymentSucceeded": true
}

+ 3
- 5
src/Services/Services.Common/CommonExtensions.cs View File

@ -289,23 +289,21 @@ public static class CommonExtensions
// {
// "EventBus": {
// "ProviderName": "ServiceBus | RabbitMQ",
// }
// }
var eventBusSection = configuration.GetRequiredSection("EventBus");
var eventBusConnectionString = configuration.GetRequiredConnectionString("EventBus");
return eventBusSection["ProviderName"]?.ToLowerInvariant() switch
{
"servicebus" => hcBuilder.AddAzureServiceBusTopic(
eventBusConnectionString,
topicName: "eshop_event_bus",
_ => configuration.GetRequiredConnectionString("EventBus"),
_ => "eshop_event_bus",
name: "servicebus",
tags: new string[] { "ready" }),
_ => hcBuilder.AddRabbitMQ(
$"amqp://{eventBusConnectionString}",
_ => $"amqp://{configuration.GetRequiredConnectionString("EventBus")}",
name: "rabbitmq",
tags: new string[] { "ready" })
};


Loading…
Cancel
Save