Skip to content

Commit

Permalink
implement auto database migration.
Browse files Browse the repository at this point in the history
  • Loading branch information
omid-ahmadpour committed Sep 13, 2024
1 parent 552dd9f commit 50cc83b
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 3 deletions.
5 changes: 3 additions & 2 deletions src/Web/Api/.config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "3.1.8",
"version": "8.0.7",
"commands": [
"dotnet-ef"
]
],
"rollForward": false
}
}
}
13 changes: 12 additions & 1 deletion src/Web/Api/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,14 @@ public static IServiceCollection AddWebApi(this IServiceCollection services, ICo
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehaviour<,>));

// Register the MigrationService
services.AddScoped<IMigrationService, MigrationService>();

return services;
}

public static IApplicationBuilder UseWebApi(this IApplicationBuilder app, IConfiguration configuration,
public static IApplicationBuilder UseWebApi(this IApplicationBuilder app,
IConfiguration configuration,
IWebHostEnvironment env)
{
app.UseCors(builder =>
Expand All @@ -92,6 +96,13 @@ public static IApplicationBuilder UseWebApi(this IApplicationBuilder app, IConfi
app.UseAuthentication();
app.UseAuthorization();

using (var scope = app.ApplicationServices.CreateScope())
{
var serviceProvider = scope.ServiceProvider;
var migrationSvc = serviceProvider.GetRequiredService<IMigrationService>();
migrationSvc.ApplyMigrations();
}

app.UseEndpoints(endpoints =>
{
if (env.IsDevelopment() || env.IsStaging())
Expand Down
42 changes: 42 additions & 0 deletions src/Web/Api/MigrationService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using CleanTemplate.Persistence.Db;
using Microsoft.EntityFrameworkCore;

namespace CleanTemplate.Api
{
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;

public interface IMigrationService
{
void ApplyMigrations();
}

public class MigrationService : IMigrationService
{
private readonly IServiceProvider _serviceProvider;

public MigrationService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}

public void ApplyMigrations()
{
using var scope = _serviceProvider.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();

// Apply Migration
try
{
context.Database.Migrate();
}
catch (Exception ex)
{
// Log the error or handle it in some way
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating the database.");
}
}
}
}

0 comments on commit 50cc83b

Please sign in to comment.