393 lines
17 KiB
C#
393 lines
17 KiB
C#
using Autofac;
|
|
using Autofac.Extensions.DependencyInjection;
|
|
using global::Catalog.API.Infrastructure.Filters;
|
|
using global::Catalog.API.IntegrationEvents;
|
|
using Microsoft.ApplicationInsights.Extensibility;
|
|
using Microsoft.ApplicationInsights.ServiceFabric;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Azure.ServiceBus;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
|
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
|
|
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
|
|
using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ;
|
|
using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus;
|
|
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF;
|
|
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services;
|
|
using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
|
|
using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.EventHandling;
|
|
using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using RabbitMQ.Client;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data.Common;
|
|
using System.Reflection;
|
|
using HealthChecks.UI.Client;
|
|
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
|
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
|
|
|
namespace Microsoft.eShopOnContainers.Services.Catalog.API
|
|
{
|
|
public class Startup
|
|
{
|
|
public Startup(IConfiguration configuration)
|
|
{
|
|
Configuration = configuration;
|
|
}
|
|
|
|
public IConfiguration Configuration { get; }
|
|
|
|
public IServiceProvider ConfigureServices(IServiceCollection services)
|
|
{
|
|
services.AddAppInsight(Configuration)
|
|
.AddCustomMVC(Configuration)
|
|
.AddCustomDbContext(Configuration)
|
|
.AddCustomOptions(Configuration)
|
|
.AddIntegrationServices(Configuration)
|
|
.AddEventBus(Configuration)
|
|
.AddSwagger()
|
|
.AddCustomHealthCheck(Configuration);
|
|
|
|
var container = new ContainerBuilder();
|
|
container.Populate(services);
|
|
return new AutofacServiceProvider(container.Build());
|
|
|
|
}
|
|
|
|
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
|
|
{
|
|
//Configure logs
|
|
|
|
//loggerFactory.AddAzureWebAppDiagnostics();
|
|
//loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);
|
|
|
|
var pathBase = Configuration["PATH_BASE"];
|
|
|
|
if (!string.IsNullOrEmpty(pathBase))
|
|
{
|
|
loggerFactory.CreateLogger<Startup>().LogDebug("Using PATH BASE '{pathBase}'", pathBase);
|
|
app.UsePathBase(pathBase);
|
|
}
|
|
|
|
app.UseHealthChecks("/hc", new HealthCheckOptions()
|
|
{
|
|
Predicate = _ => true,
|
|
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
|
|
});
|
|
|
|
app.UseHealthChecks("/liveness", new HealthCheckOptions
|
|
{
|
|
Predicate = r => r.Name.Contains("self")
|
|
});
|
|
|
|
app.UseCors("CorsPolicy");
|
|
|
|
app.UseMvcWithDefaultRoute();
|
|
|
|
app.UseSwagger()
|
|
.UseSwaggerUI(c =>
|
|
{
|
|
c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Catalog.API V1");
|
|
});
|
|
|
|
ConfigureEventBus(app);
|
|
}
|
|
|
|
protected virtual void ConfigureEventBus(IApplicationBuilder app)
|
|
{
|
|
var eventBus = app.ApplicationServices.GetRequiredService<IMultiEventBus>();
|
|
eventBus.Subscribe<OrderStatusChangedToAwaitingValidationIntegrationEvent, OrderStatusChangedToAwaitingValidationIntegrationEventHandler>();
|
|
eventBus.Subscribe<OrderStatusChangedToPaidIntegrationEvent, OrderStatusChangedToPaidIntegrationEventHandler>();
|
|
}
|
|
}
|
|
|
|
public static class CustomExtensionMethods
|
|
{
|
|
public static IServiceCollection AddAppInsight(this IServiceCollection services, IConfiguration configuration)
|
|
{
|
|
services.AddApplicationInsightsTelemetry(configuration);
|
|
var orchestratorType = configuration.GetValue<string>("OrchestratorType");
|
|
|
|
if (orchestratorType?.ToUpper() == "K8S")
|
|
{
|
|
// Enable K8s telemetry initializer
|
|
services.AddApplicationInsightsKubernetesEnricher();
|
|
}
|
|
if (orchestratorType?.ToUpper() == "SF")
|
|
{
|
|
// Enable SF telemetry initializer
|
|
services.AddSingleton<ITelemetryInitializer>((serviceProvider) =>
|
|
new FabricTelemetryInitializer());
|
|
}
|
|
|
|
return services;
|
|
}
|
|
|
|
public static IServiceCollection AddCustomMVC(this IServiceCollection services, IConfiguration configuration)
|
|
{
|
|
services.AddMvc(options =>
|
|
{
|
|
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
|
|
})
|
|
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
|
|
.AddControllersAsServices();
|
|
|
|
services.AddCors(options =>
|
|
{
|
|
options.AddPolicy("CorsPolicy",
|
|
builder => builder
|
|
.SetIsOriginAllowed((host) => true)
|
|
.AllowAnyMethod()
|
|
.AllowAnyHeader()
|
|
.AllowCredentials());
|
|
});
|
|
|
|
return services;
|
|
}
|
|
|
|
public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration)
|
|
{
|
|
var accountName = configuration.GetValue<string>("AzureStorageAccountName");
|
|
var accountKey = configuration.GetValue<string>("AzureStorageAccountKey");
|
|
|
|
var hcBuilder = services.AddHealthChecks();
|
|
|
|
hcBuilder
|
|
.AddCheck("self", () => HealthCheckResult.Healthy())
|
|
.AddSqlServer(
|
|
configuration["ConnectionString"],
|
|
name: "CatalogDB-check",
|
|
tags: new string[] { "catalogdb" });
|
|
|
|
if (!string.IsNullOrEmpty(accountName) && !string.IsNullOrEmpty(accountKey))
|
|
{
|
|
hcBuilder
|
|
.AddAzureBlobStorage(
|
|
$"DefaultEndpointsProtocol=https;AccountName={accountName};AccountKey={accountKey};EndpointSuffix=core.windows.net",
|
|
name: "catalog-storage-check",
|
|
tags: new string[] { "catalogstorage" });
|
|
}
|
|
|
|
if (configuration.GetValue<bool>("AzureServiceBusEnabled"))
|
|
{
|
|
hcBuilder
|
|
.AddAzureServiceBusTopic(
|
|
configuration["EventBusConnection"],
|
|
topicName: "eshop_event_bus",
|
|
name: "catalog-servicebus-check",
|
|
tags: new string[] { "servicebus" });
|
|
}
|
|
else
|
|
{
|
|
hcBuilder
|
|
.AddRabbitMQ(
|
|
$"amqp://{configuration["EventBusConnection"]}",
|
|
name: "catalog-rabbitmqbus-check",
|
|
tags: new string[] { "rabbitmqbus" });
|
|
}
|
|
|
|
return services;
|
|
}
|
|
|
|
public static IServiceCollection AddCustomDbContext(this IServiceCollection services, IConfiguration configuration)
|
|
{
|
|
services.AddDbContext<CatalogContext>(options =>
|
|
{
|
|
options.UseSqlServer(configuration["ConnectionString"],
|
|
sqlServerOptionsAction: sqlOptions =>
|
|
{
|
|
sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
|
|
//Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
|
|
sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
|
|
});
|
|
|
|
// Changing default behavior when client evaluation occurs to throw.
|
|
// Default in EF Core would be to log a warning when client evaluation is performed.
|
|
options.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
|
|
//Check Client vs. Server evaluation: https://docs.microsoft.com/en-us/ef/core/querying/client-eval
|
|
});
|
|
|
|
services.AddDbContext<IntegrationEventLogContext>(options =>
|
|
{
|
|
options.UseSqlServer(configuration["ConnectionString"],
|
|
sqlServerOptionsAction: sqlOptions =>
|
|
{
|
|
sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
|
|
//Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
|
|
sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
|
|
});
|
|
});
|
|
|
|
return services;
|
|
}
|
|
|
|
public static IServiceCollection AddCustomOptions(this IServiceCollection services, IConfiguration configuration)
|
|
{
|
|
services.Configure<CatalogSettings>(configuration);
|
|
services.Configure<ApiBehaviorOptions>(options =>
|
|
{
|
|
options.InvalidModelStateResponseFactory = context =>
|
|
{
|
|
var problemDetails = new ValidationProblemDetails(context.ModelState)
|
|
{
|
|
Instance = context.HttpContext.Request.Path,
|
|
Status = StatusCodes.Status400BadRequest,
|
|
Detail = "Please refer to the errors property for additional details."
|
|
};
|
|
|
|
return new BadRequestObjectResult(problemDetails)
|
|
{
|
|
ContentTypes = { "application/problem+json", "application/problem+xml" }
|
|
};
|
|
};
|
|
});
|
|
|
|
return services;
|
|
}
|
|
|
|
public static IServiceCollection AddSwagger(this IServiceCollection services)
|
|
{
|
|
services.AddSwaggerGen(options =>
|
|
{
|
|
options.DescribeAllEnumsAsStrings();
|
|
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
|
|
{
|
|
Title = "eShopOnContainers - Catalog HTTP API",
|
|
Version = "v1",
|
|
Description = "The Catalog Microservice HTTP API. This is a Data-Driven/CRUD microservice sample",
|
|
TermsOfService = "Terms Of Service"
|
|
});
|
|
});
|
|
|
|
return services;
|
|
|
|
}
|
|
|
|
public static IServiceCollection AddIntegrationServices(this IServiceCollection services, IConfiguration configuration)
|
|
{
|
|
services.AddTransient<Func<DbConnection, IIntegrationEventLogService>>(
|
|
sp => (DbConnection c) => new IntegrationEventLogService(c));
|
|
|
|
services.AddTransient<ICatalogIntegrationEventService, CatalogIntegrationEventService>();
|
|
|
|
services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
|
|
{
|
|
var settings = sp.GetRequiredService<IOptions<CatalogSettings>>().Value;
|
|
var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
|
|
|
|
var factory = new ConnectionFactory()
|
|
{
|
|
HostName = configuration["EventBusConnection"],
|
|
DispatchConsumersAsync = true
|
|
};
|
|
|
|
if (!string.IsNullOrEmpty(configuration["EventBusUserName"]))
|
|
{
|
|
factory.UserName = configuration["EventBusUserName"];
|
|
}
|
|
|
|
if (!string.IsNullOrEmpty(configuration["EventBusPassword"]))
|
|
{
|
|
factory.Password = configuration["EventBusPassword"];
|
|
}
|
|
|
|
factory.VirtualHost = "TenantA";
|
|
|
|
var retryCount = 5;
|
|
if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"]))
|
|
{
|
|
retryCount = int.Parse(configuration["EventBusRetryCount"]);
|
|
}
|
|
|
|
return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
|
|
});
|
|
|
|
services.AddSingleton<IMultiRabbitMQPersistentConnections>(sp =>
|
|
{
|
|
IMultiRabbitMQPersistentConnections connections = new MultiRabbitMQPersistentConnections();
|
|
connections.AddConnection(GenerateConnection("TenantA", sp, configuration));
|
|
connections.AddConnection(GenerateConnection("TenantB", sp, configuration));
|
|
|
|
return connections;
|
|
});
|
|
return services;
|
|
}
|
|
|
|
|
|
private static IRabbitMQPersistentConnection GenerateConnection(String vHost, IServiceProvider sp, IConfiguration configuration)
|
|
{
|
|
var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
|
|
|
|
var factory = new ConnectionFactory()
|
|
{
|
|
HostName = configuration["EventBusConnection"],
|
|
DispatchConsumersAsync = true
|
|
};
|
|
|
|
if (!string.IsNullOrEmpty(configuration["EventBusUserName"]))
|
|
{
|
|
factory.UserName = configuration["EventBusUserName"];
|
|
}
|
|
|
|
if (!string.IsNullOrEmpty(configuration["EventBusPassword"]))
|
|
{
|
|
factory.Password = configuration["EventBusPassword"];
|
|
}
|
|
|
|
factory.VirtualHost = vHost;
|
|
|
|
var retryCount = 5;
|
|
if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"]))
|
|
{
|
|
retryCount = int.Parse(configuration["EventBusRetryCount"]);
|
|
}
|
|
|
|
return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
|
|
}
|
|
|
|
public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration)
|
|
{
|
|
var subscriptionClientName = configuration["SubscriptionClientName"];
|
|
|
|
services.AddSingleton<IMultiEventBus, MultiEventBusRabbitMQ>(sp =>
|
|
{
|
|
var multiRabbitMqPersistentConnections = sp.GetRequiredService<IMultiRabbitMQPersistentConnections>();
|
|
var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
|
|
var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>();
|
|
var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
|
|
|
|
var retryCount = 5;
|
|
if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"]))
|
|
{
|
|
retryCount = int.Parse(configuration["EventBusRetryCount"]);
|
|
}
|
|
|
|
List<IEventBus> eventBuses = new List<IEventBus>();
|
|
|
|
eventBuses.Add(new EventBusRabbitMQ(multiRabbitMqPersistentConnections.GetConnections()[0], logger,
|
|
iLifetimeScope, eventBusSubcriptionsManager, "TenantA", subscriptionClientName, retryCount));
|
|
eventBuses.Add(new EventBusRabbitMQ(multiRabbitMqPersistentConnections.GetConnections()[1], logger,
|
|
iLifetimeScope, eventBusSubcriptionsManager, "TenantB", subscriptionClientName, retryCount));
|
|
Dictionary<int, String> tenants = new Dictionary<int, string>();
|
|
tenants.Add(1, "TenantA");
|
|
tenants.Add(2, "TenantB");
|
|
|
|
return new MultiEventBusRabbitMQ(eventBuses, tenants);
|
|
});
|
|
|
|
services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
|
|
services.AddTransient<OrderStatusChangedToAwaitingValidationIntegrationEventHandler>();
|
|
services.AddTransient<OrderStatusChangedToPaidIntegrationEventHandler>();
|
|
|
|
return services;
|
|
}
|
|
}
|
|
}
|