242 lines
11 KiB
C#
Raw Normal View History

2016-11-03 17:52:15 +01:00
namespace Microsoft.eShopOnContainers.Services.Catalog.API
{
using Autofac;
using Autofac.Extensions.DependencyInjection;
using global::Catalog.API.Infrastructure.Filters;
2017-04-17 12:28:12 +02:00
using global::Catalog.API.IntegrationEvents;
2016-11-03 17:52:15 +01:00
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Azure.ServiceBus;
2016-11-03 17:52:15 +01:00
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
2016-11-03 17:52:15 +01:00
using Microsoft.EntityFrameworkCore.Infrastructure;
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;
2017-03-24 12:37:44 +01:00
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services;
2016-11-03 17:52:15 +01:00
using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.EventHandling;
using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events;
2016-11-03 17:52:15 +01:00
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
2017-03-23 19:10:55 +01:00
using Microsoft.Extensions.HealthChecks;
2016-11-03 17:52:15 +01:00
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Polly;
using RabbitMQ.Client;
using System;
2017-03-24 12:37:44 +01:00
using System.Data.Common;
2017-04-17 12:28:12 +02:00
using System.Data.SqlClient;
2017-03-03 12:03:31 +01:00
using System.Reflection;
using System.Threading.Tasks;
2016-11-03 17:52:15 +01:00
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
2017-04-17 12:28:12 +02:00
2017-03-23 19:10:55 +01:00
services.AddHealthChecks(checks =>
{
var minutes = 1;
if (int.TryParse(Configuration["HealthCheck:Timeout"], out var minutesParsed))
{
minutes = minutesParsed;
}
checks.AddSqlCheck("CatalogDb", Configuration["ConnectionString"], TimeSpan.FromMinutes(minutes));
var accountName = Configuration.GetValue<string>("AzureStorageAccountName");
var accountKey = Configuration.GetValue<string>("AzureStorageAccountKey");
if (!string.IsNullOrEmpty(accountName) && !string.IsNullOrEmpty(accountKey))
{
checks.AddAzureBlobStorageCheck(accountName, accountKey);
}
2017-03-23 19:10:55 +01:00
});
2017-03-28 16:37:48 +02:00
services.AddMvc(options =>
{
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
}).AddControllersAsServices();
2017-03-27 15:24:29 +02:00
services.AddDbContext<CatalogContext>(options =>
{
options.UseSqlServer(Configuration["ConnectionString"],
sqlServerOptionsAction: sqlOptions =>
2017-04-17 12:28:12 +02:00
{
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: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
});
2017-04-17 12:28:12 +02:00
// 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
});
2017-04-17 12:28:12 +02:00
services.Configure<CatalogSettings>(Configuration);
// Add framework services.
services.AddSwaggerGen(options =>
2016-11-03 17:52:15 +01:00
{
options.DescribeAllEnumsAsStrings();
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
2016-11-03 17:52:15 +01:00
{
Title = "eShopOnContainers - Catalog HTTP API",
2016-11-03 17:52:15 +01:00
Version = "v1",
Description = "The Catalog Microservice HTTP API. This is a Data-Driven/CRUD microservice sample",
TermsOfService = "Terms Of Service"
2016-11-03 17:52:15 +01:00
});
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
2017-03-24 12:37:44 +01:00
services.AddTransient<Func<DbConnection, IIntegrationEventLogService>>(
2017-04-17 12:28:12 +02:00
sp => (DbConnection c) => new IntegrationEventLogService(c));
services.AddTransient<ICatalogIntegrationEventService, CatalogIntegrationEventService>();
2017-04-17 12:28:12 +02:00
2017-05-24 19:23:14 +02:00
if (Configuration.GetValue<bool>("AzureServiceBusEnabled"))
2017-04-17 12:28:12 +02:00
{
services.AddSingleton<IServiceBusPersisterConnection>(sp =>
{
var settings = sp.GetRequiredService<IOptions<CatalogSettings>>().Value;
var logger = sp.GetRequiredService<ILogger<DefaultServiceBusPersisterConnection>>();
2017-05-30 17:59:57 +02:00
var serviceBusConnection = new ServiceBusConnectionStringBuilder(settings.EventBusConnection);
return new DefaultServiceBusPersisterConnection(serviceBusConnection, logger);
});
}
else
{
services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
{
var settings = sp.GetRequiredService<IOptions<CatalogSettings>>().Value;
var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
var factory = new ConnectionFactory()
{
HostName = settings.EventBusConnection
};
return new DefaultRabbitMQPersistentConnection(factory, logger);
});
}
2017-05-26 01:35:44 +02:00
RegisterEventBus(services);
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//Configure logs
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors("CorsPolicy");
app.UseMvcWithDefaultRoute();
2016-11-03 17:52:15 +01:00
app.UseSwagger()
.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
var context = (CatalogContext)app
.ApplicationServices.GetService(typeof(CatalogContext));
2017-06-20 12:54:32 -07:00
WaitForSqlAvailabilityAsync(context, loggerFactory, app, env).Wait();
2017-03-24 12:37:44 +01:00
ConfigureEventBus(app);
2017-03-24 12:37:44 +01:00
var integrationEventLogContext = new IntegrationEventLogContext(
new DbContextOptionsBuilder<IntegrationEventLogContext>()
.UseSqlServer(Configuration["ConnectionString"], b => b.MigrationsAssembly("Catalog.API"))
2017-03-24 12:37:44 +01:00
.Options);
2017-04-17 12:28:12 +02:00
integrationEventLogContext.Database.Migrate();
}
2017-06-20 12:54:32 -07:00
private async Task WaitForSqlAvailabilityAsync(CatalogContext ctx, ILoggerFactory loggerFactory, IApplicationBuilder app, IHostingEnvironment env, int retries = 0)
{
var logger = loggerFactory.CreateLogger(nameof(Startup));
var policy = CreatePolicy(retries, logger, nameof(WaitForSqlAvailabilityAsync));
await policy.ExecuteAsync(async () =>
2017-04-17 12:28:12 +02:00
{
2017-06-20 12:54:32 -07:00
await CatalogContextSeed.SeedAsync(app, env, loggerFactory);
});
}
private Policy CreatePolicy(int retries, ILogger logger, string prefix)
{
return Policy.Handle<SqlException>().
WaitAndRetryAsync(
retryCount: retries,
sleepDurationProvider: retry => TimeSpan.FromSeconds(5),
onRetry: (exception, timeSpan, retry, ctx) =>
{
logger.LogTrace($"[{prefix}] Exception {exception.GetType().Name} with message ${exception.Message} detected on attempt {retry} of {retries}");
}
);
}
2017-05-26 01:35:44 +02:00
private void RegisterEventBus(IServiceCollection services)
2017-05-17 00:40:40 +02:00
{
2017-05-24 19:23:14 +02:00
if (Configuration.GetValue<bool>("AzureServiceBusEnabled"))
{
services.AddSingleton<IEventBus, EventBusServiceBus>(sp =>
{
var serviceBusPersisterConnection = sp.GetRequiredService<IServiceBusPersisterConnection>();
2017-06-26 18:05:02 +02:00
var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
var logger = sp.GetRequiredService<ILogger<EventBusServiceBus>>();
var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
var subscriptionClientName = Configuration["SubscriptionClientName"];
return new EventBusServiceBus(serviceBusPersisterConnection, logger,
2017-06-26 18:05:02 +02:00
eventBusSubcriptionsManager, subscriptionClientName, iLifetimeScope);
});
2017-05-17 00:40:40 +02:00
}
else
{
services.AddSingleton<IEventBus, EventBusRabbitMQ>();
}
2017-05-17 00:40:40 +02:00
services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
services.AddTransient<OrderStatusChangedToAwaitingValidationIntegrationEventHandler>();
services.AddTransient<OrderStatusChangedToPaidIntegrationEventHandler>();
2017-05-17 00:40:40 +02:00
}
2017-05-26 01:35:44 +02:00
protected virtual void ConfigureEventBus(IApplicationBuilder app)
{
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<OrderStatusChangedToAwaitingValidationIntegrationEvent, OrderStatusChangedToAwaitingValidationIntegrationEventHandler>();
eventBus.Subscribe<OrderStatusChangedToPaidIntegrationEvent, OrderStatusChangedToPaidIntegrationEventHandler>();
}
}
}