Skip to content

Commit

Permalink
Speed up assembly scanning
Browse files Browse the repository at this point in the history
  • Loading branch information
hhvrc committed Nov 22, 2024
1 parent 94d39e5 commit 67c52b2
Showing 1 changed file with 12 additions and 13 deletions.
25 changes: 12 additions & 13 deletions Common/Utils/Migration/MigrationExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations;
using System.Reflection;

namespace OpenShock.Common.Utils.Migration;
Expand All @@ -7,19 +8,6 @@ public static class MigrationExtensions
{
private static KeyValuePair<string, ComplexMigrationBase<TDbContext>>? GetComplexMigrationRecord<TDbContext>(this Type type) where TDbContext : DbContext
{
if (!type.IsClass) return null; // Hot path

if (!typeof(Microsoft.EntityFrameworkCore.Migrations.Migration).IsAssignableFrom(type))
{
return null;
}

var migrationId = type.GetCustomAttribute<Microsoft.EntityFrameworkCore.Migrations.MigrationAttribute>(false)?.Id;
if (string.IsNullOrEmpty(migrationId))
{
return null;
}

var complexMigrationType = type
.GetCustomAttributes(false)
.Select(x => x.GetType())
Expand All @@ -32,16 +20,27 @@ public static class MigrationExtensions
return null;
}

var migrationId = type.GetCustomAttribute<Microsoft.EntityFrameworkCore.Migrations.MigrationAttribute>(false)?.Id;
if (string.IsNullOrEmpty(migrationId))
{
return null;
}


var complexMigrationInstance = Activator.CreateInstance(complexMigrationType) as ComplexMigrationBase<TDbContext> ?? throw new Exception("Failed to instanciate ComplexMigrationBase");

return new KeyValuePair<string, ComplexMigrationBase<TDbContext>>(migrationId, complexMigrationInstance);
}

private static Dictionary<string, ComplexMigrationBase<TDbContext>> GetComplexMigrations<TDbContext>(this TDbContext context) where TDbContext : DbContext
{
var efcoreMigrationType = typeof(Microsoft.EntityFrameworkCore.Migrations.Migration);

return AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(asm => asm.GetTypes())
.Where(type => type.IsClass)
.Where(efcoreMigrationType.IsAssignableFrom)
.Select(GetComplexMigrationRecord<TDbContext>)
.Where(record => record.HasValue)
.Select(record => record!.Value)
Expand Down

0 comments on commit 67c52b2

Please sign in to comment.