Review MigrateDbContext to add retry for network-related exception when sql server container is created

This commit is contained in:
Unai Zorrilla Castro 2017-11-02 15:03:32 +01:00
parent 97a4659277
commit 8b264e0767
2 changed files with 22 additions and 2 deletions

View File

@ -6,6 +6,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" /> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Polly" Version="5.3.1" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,7 +1,10 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Polly;
using Polly.Retry;
using System; using System;
using System.Data.SqlClient;
namespace Microsoft.AspNetCore.Hosting namespace Microsoft.AspNetCore.Hosting
{ {
@ -21,10 +24,26 @@ namespace Microsoft.AspNetCore.Hosting
{ {
logger.LogInformation($"Migrating database associated with context {typeof(TContext).Name}"); logger.LogInformation($"Migrating database associated with context {typeof(TContext).Name}");
context.Database var retry = Policy.Handle<SqlException>()
.WaitAndRetry(new TimeSpan[]
{
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(15),
});
retry.Execute(() =>
{
//if the sql server container is not created on run docker compose this
//migration can't fail for network related exception. The retry options for DbContext only
//apply to transient exceptions.
context.Database
.Migrate(); .Migrate();
seeder(context,services); seeder(context, services);
});
logger.LogInformation($"Migrated database associated with context {typeof(TContext).Name}"); logger.LogInformation($"Migrated database associated with context {typeof(TContext).Name}");
} }