|
20 | 20 | using Infrastructure.Repositories; |
21 | 21 | using Autofac; |
22 | 22 | using Autofac.Extensions.DependencyInjection; |
| 23 | + using Polly; |
| 24 | + using System.Threading.Tasks; |
| 25 | + using System.Data.SqlClient; |
23 | 26 |
|
24 | 27 | public class Startup |
25 | 28 | { |
@@ -133,10 +136,12 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF |
133 | 136 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); |
134 | 137 | }); |
135 | 138 |
|
136 | | - ConfigureEventBus(app); |
| 139 | + var context = (MarketingContext)app |
| 140 | + .ApplicationServices.GetService(typeof(MarketingContext)); |
| 141 | + |
| 142 | + WaitForSqlAvailabilityAsync(context, loggerFactory, app).Wait(); |
137 | 143 |
|
138 | | - MarketingContextSeed.SeedAsync(app, loggerFactory) |
139 | | - .Wait(); |
| 144 | + ConfigureEventBus(app); |
140 | 145 | } |
141 | 146 |
|
142 | 147 | protected virtual void ConfigureAuth(IApplicationBuilder app) |
@@ -166,5 +171,28 @@ private void ConfigureEventBus(IApplicationBuilder app) |
166 | 171 | eventBus.Subscribe<UserLocationUpdatedIntegrationEvent, |
167 | 172 | IIntegrationEventHandler<UserLocationUpdatedIntegrationEvent>>(); |
168 | 173 | } |
| 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 | + } |
169 | 197 | } |
170 | 198 | } |
0 commit comments