Bulk register IEntityTypeConfiguration<> entity framework core
Answer from @Evk is a bit outdated and does not work any more, answer from @paul van bladel is the working one, though it contains hardcoded strings, I have utmost hatered for. In case someone shares my feeling I would like to propose my solution in form of creating static extension method:
public static ModelBuilder ApplyAllConfigurationsFromAssembly(
this ModelBuilder modelBuilder, Assembly assembly)
{
var applyGenericMethod = typeof(ModelBuilder)
.GetMethods(BindingFlags.Instance | BindingFlags.Public)
.Single(m => m.Name == nameof(ModelBuilder.ApplyConfiguration)
&& m.GetParameters().Count() == 1
&& m.GetParameters().Single().ParameterType.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>));
foreach (var type in assembly.GetTypes()
.Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters))
{
foreach (var iface in type.GetInterfaces())
{
if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))
{
var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
applyConcreteMethod.Invoke(modelBuilder, new object[] {Activator.CreateInstance(type)});
break;
}
}
}
}
And, if your configuration classes are stored in the same assembly as your DbContext you use this method as follows:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyAllConfigurationsFromAssembly(GetType().Assembly);
base.OnModelCreating(modelBuilder);
}
It can be done with reflection like this:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// get ApplyConfiguration method with reflection
var applyGenericMethod = typeof(ModelBuilder).GetMethod("ApplyConfiguration", BindingFlags.Instance | BindingFlags.Public);
// replace GetExecutingAssembly with assembly where your configurations are if necessary
foreach (var type in Assembly.GetExecutingAssembly().GetTypes()
.Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters))
{
// use type.Namespace to filter by namespace if necessary
foreach (var iface in type.GetInterfaces()) {
// if type implements interface IEntityTypeConfiguration<SomeEntity>
if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>)) {
// make concrete ApplyConfiguration<SomeEntity> method
var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
// and invoke that with fresh instance of your configuration type
applyConcreteMethod.Invoke(modelBuilder, new object[] {Activator.CreateInstance(type)});
break;
}
}
}
}
The nice work from @Evk kan be further encapsulated in a reusable extension method:
public static class ModelBuilderExtensions
{
public static void ApplyAllConfigurationsFromCurrentAssembly(this ModelBuilder modelBuilder, Assembly assembly, string configNamespace = "")
{
var applyGenericMethods = typeof(ModelBuilder).GetMethods( BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
var applyGenericApplyConfigurationMethods = applyGenericMethods.Where(m => m.IsGenericMethod && m.Name.Equals("ApplyConfiguration", StringComparison.OrdinalIgnoreCase));
var applyGenericMethod = applyGenericApplyConfigurationMethods.Where(m=>m.GetParameters().FirstOrDefault().ParameterType.Name== "IEntityTypeConfiguration`1").FirstOrDefault();
var applicableTypes = assembly
.GetTypes()
.Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters);
if (!string.IsNullOrEmpty(configNamespace))
{
applicableTypes = applicableTypes.Where(c => c.Namespace == configNamespace);
}
foreach (var type in applicableTypes)
{
foreach (var iface in type.GetInterfaces())
{
// if type implements interface IEntityTypeConfiguration<SomeEntity>
if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))
{
// make concrete ApplyConfiguration<SomeEntity> method
var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
// and invoke that with fresh instance of your configuration type
applyConcreteMethod.Invoke(modelBuilder, new object[] { Activator.CreateInstance(type) });
Console.WriteLine("applied model " + type.Name);
break;
}
}
}
}
}
And can be called as such:
public class ApiDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public ApiDbContext(DbContextOptions<ApiDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyAllConfigurationsFromCurrentAssembly("MyRoot.Api.Entities.Configuration");
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
}
Using EF Core 2.2+, it got much simpler:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
Assembly assemblyWithConfigurations = GetType().Assembly; //get whatever assembly you want
modelBuilder.ApplyConfigurationsFromAssembly(assemblyWithConfigurations);
}