Skip to content

Commit cd1a091

Browse files
committed
Add polly to marketing api
1 parent ed7dfc7 commit cd1a091

1 file changed

Lines changed: 31 additions & 3 deletions

File tree

src/Services/Marketing/Marketing.API/Startup.cs

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020
using Infrastructure.Repositories;
2121
using Autofac;
2222
using Autofac.Extensions.DependencyInjection;
23+
using Polly;
24+
using System.Threading.Tasks;
25+
using System.Data.SqlClient;
2326

2427
public class Startup
2528
{
@@ -133,10 +136,12 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
133136
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
134137
});
135138

136-
ConfigureEventBus(app);
139+
var context = (MarketingContext)app
140+
.ApplicationServices.GetService(typeof(MarketingContext));
141+
142+
WaitForSqlAvailabilityAsync(context, loggerFactory, app).Wait();
137143

138-
MarketingContextSeed.SeedAsync(app, loggerFactory)
139-
.Wait();
144+
ConfigureEventBus(app);
140145
}
141146

142147
protected virtual void ConfigureAuth(IApplicationBuilder app)
@@ -166,5 +171,28 @@ private void ConfigureEventBus(IApplicationBuilder app)
166171
eventBus.Subscribe<UserLocationUpdatedIntegrationEvent,
167172
IIntegrationEventHandler<UserLocationUpdatedIntegrationEvent>>();
168173
}
174+
175+
private async Task WaitForSqlAvailabilityAsync(MarketingContext ctx, ILoggerFactory loggerFactory, IApplicationBuilder app, int retries = 0)
176+
{
177+
var logger = loggerFactory.CreateLogger(nameof(Startup));
178+
var policy = CreatePolicy(retries, logger, nameof(WaitForSqlAvailabilityAsync));
179+
await policy.ExecuteAsync(async () =>
180+
{
181+
await MarketingContextSeed.SeedAsync(app, loggerFactory);
182+
});
183+
}
184+
185+
private Policy CreatePolicy(int retries, ILogger logger, string prefix)
186+
{
187+
return Policy.Handle<SqlException>().
188+
WaitAndRetryAsync(
189+
retryCount: retries,
190+
sleepDurationProvider: retry => TimeSpan.FromSeconds(5),
191+
onRetry: (exception, timeSpan, retry, ctx) =>
192+
{
193+
logger.LogTrace($"[{prefix}] Exception {exception.GetType().Name} with message ${exception.Message} detected on attempt {retry} of {retries}");
194+
}
195+
);
196+
}
169197
}
170198
}

0 commit comments

Comments
 (0)