From cd1a091b6f6e5421963e629c7f32955b32b2e814 Mon Sep 17 00:00:00 2001 From: Christian Arenas Date: Thu, 15 Jun 2017 19:26:24 +0200 Subject: [PATCH] Add polly to marketing api --- .../Marketing/Marketing.API/Startup.cs | 34 +++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/src/Services/Marketing/Marketing.API/Startup.cs b/src/Services/Marketing/Marketing.API/Startup.cs index 20eb97a12..a31055d39 100644 --- a/src/Services/Marketing/Marketing.API/Startup.cs +++ b/src/Services/Marketing/Marketing.API/Startup.cs @@ -20,6 +20,9 @@ using Infrastructure.Repositories; using Autofac; using Autofac.Extensions.DependencyInjection; + using Polly; + using System.Threading.Tasks; + using System.Data.SqlClient; public class Startup { @@ -133,10 +136,12 @@ c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); - ConfigureEventBus(app); + var context = (MarketingContext)app + .ApplicationServices.GetService(typeof(MarketingContext)); + + WaitForSqlAvailabilityAsync(context, loggerFactory, app).Wait(); - MarketingContextSeed.SeedAsync(app, loggerFactory) - .Wait(); + ConfigureEventBus(app); } protected virtual void ConfigureAuth(IApplicationBuilder app) @@ -166,5 +171,28 @@ eventBus.Subscribe>(); } + + private async Task WaitForSqlAvailabilityAsync(MarketingContext ctx, ILoggerFactory loggerFactory, IApplicationBuilder app, int retries = 0) + { + var logger = loggerFactory.CreateLogger(nameof(Startup)); + var policy = CreatePolicy(retries, logger, nameof(WaitForSqlAvailabilityAsync)); + await policy.ExecuteAsync(async () => + { + await MarketingContextSeed.SeedAsync(app, loggerFactory); + }); + } + + private Policy CreatePolicy(int retries, ILogger logger, string prefix) + { + return Policy.Handle(). + 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}"); + } + ); + } } }