Skip to content

Add ApplyConfiguration() overloads to ModelBuilder that scans assemblies #13088

Closed

Description

@rmja

It would be neat with an overload on ModelBuilder that scanned assemblies for IEntityTypeConfiguration and IQueryTypeConfiguration classes. The use would be:

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(GetType().Assembly, someOtherAssemblyWithEntityTypes);
        }

I currently use this extension method to accomplish this, but it uses reflection to do its job. (It only supports IEntityTypeConfiguration and not IQueryTypeConfiguration):

public static class EntityTypeConfigurationModelBuilderExtensions
    {
        private static readonly ConcurrentDictionary<Type, Func<ModelBuilder, ModelBuilder>> _applyEntityTypeConfigurationDelegates = new ConcurrentDictionary<Type, Func<ModelBuilder, ModelBuilder>>();
        private static readonly ConcurrentDictionary<Assembly, Type[]> _assemblyConfiguratorTypes = new ConcurrentDictionary<Assembly, Type[]>();

        /// <summary>
        /// Apply configuration for the entity configurator of <paramref name="configuratorType"/>.
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="configuratorType">The configurator implementing <see cref="IEntityTypeConfiguration{TEntity}"/></param>
        public static void ApplyEntityTypeConfiguration(this ModelBuilder builder, Type configuratorType)
        {
            var applyConfigurationDelegate = _applyEntityTypeConfigurationDelegates.GetOrAdd(configuratorType, GetApplyEntityTypeConfigurationDelegate);

            applyConfigurationDelegate(builder);
        }

        private static Func<ModelBuilder, ModelBuilder> GetApplyEntityTypeConfigurationDelegate(Type configuratorType)
        {
            var configurator = Activator.CreateInstance(configuratorType);

            var genericConfiguratorInterfaceType = configuratorType.GetInterfaces().Single(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>));
            var entityType = genericConfiguratorInterfaceType.GetGenericArguments()[0];

            var modelBuilderInstance = Expression.Parameter(typeof(ModelBuilder), "modelBuilder");

            return Expression.Lambda<Func<ModelBuilder, ModelBuilder>>(
                Expression.Call(
                    modelBuilderInstance,
                    typeof(ModelBuilder).GetMethods().Single(IsApplyEntityTypeConfigurationMethod).MakeGenericMethod(entityType),
                    Expression.Convert(Expression.Constant(configurator), typeof(IEntityTypeConfiguration<>).MakeGenericType(entityType))),
                modelBuilderInstance).Compile();
        }

        private static bool IsApplyEntityTypeConfigurationMethod(MethodInfo methodInfo)
        {
            if (methodInfo.Name == nameof(ModelBuilder.ApplyConfiguration))
            {
                var parameters = methodInfo.GetParameters();

                return parameters.Length == 1 && parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>);
            }

            return false;
        }

        /// <summary>
        /// Apply configuration for all entity configurators defined in <paramref name="assemblies"/>.
        /// </summary>
        /// <param name="builder">The model builder</param>
        /// <param name="assemblies">The assemblies to scan for <see cref="IEntityTypeConfiguration{TEntity}"></see></param>
        public static void ApplyConfiguration(this ModelBuilder builder, params Assembly[] assemblies)
        {
            foreach (var assembly in assemblies)
            {
                var entityConfiguratorTypes = _assemblyConfiguratorTypes.GetOrAdd(assembly, GetEntityTypeConfiguratorTypes);

                foreach (var type in entityConfiguratorTypes)
                {
                    builder.ApplyEntityTypeConfiguration(type);
                }
            }
        }

        private static Type[] GetEntityTypeConfiguratorTypes(Assembly assembly) => assembly.ExportedTypes.Where(IsEntityConfigurator).ToArray();

        private static bool IsEntityConfigurator(Type type) => type.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>));
    }

Activity

  1. ajcvickers commented on Aug 23, 2018

    @ajcvickers
    Contributor

    Duplicate of #13014, but bringing this back to triage since we are seeing many requests for it.

  2. ajcvickers commented on Aug 29, 2018

    @ajcvickers
    Contributor

    We discussed this again in triage and since it seems to be a very popular request we will consider adding some API to discover and register IEntityTypeConfigurations from a given assembly. This would always be opt-in, meaning that to use it an explicit call must be made, and should take the Assembly to look in as a parameter.

  3. added this to the Backlog milestone on Aug 29, 2018
  4. added
    help wanted
    on Aug 29, 2018
  5. DSilence commented on Sep 4, 2018

    @DSilence
    Contributor

    I'm willing to take a look at this if nobody minds.

  6. added 4 commits that reference this issue on Sep 12, 2018
  7. added a commit that references this issue on Oct 5, 2018
  8. added a commit that references this issue on Oct 5, 2018
  9. modified the milestones: Backlog, on Oct 5, 2018
  10. added and removed
    help wanted
    on Oct 5, 2018
  11. ajcvickers commented on Oct 5, 2018

    @ajcvickers
    Contributor

    @DSilence Thanks for contributing this!

  12. modified the milestones: , 2.2.0 on Nov 11, 2019
  13. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions