Home > Net >  Getting classes that Inherits interface<Type:Type>
Getting classes that Inherits interface<Type:Type>

Time:03-01

Here is my problem I want get all of my fluent api configuration classes as a list. And then apply them in my DbContext. My domain Classes all Inherits BaseModel like this ;

public class Role : BaseModel
{
    public string RoleTitle { get; set; }

    public string RoleDescription { get; set; }

    public ICollection<UserRole> UserRoles { get; set; }
}

And configs like this :

public class RoleConfig : IEntityTypeConfiguration<Role>
{
  public void Configure(EntityTypeBuilder<Role> builder)
  {
      builder.Property(r => r.RoleTitle)
          .IsRequired()
          .HasMaxLength(100);

      builder.Property(r => r.RoleDescription)
        .HasMaxLength(250);
  }
}

And what i already use in my DbContext is:

    modelBuilder.ApplyConfiguration(new UserConfig());
    modelBuilder.ApplyConfiguration(new RoleConfig());
    modelBuilder.ApplyConfiguration(new UserRoleConfig());
    and more .....

And what i am looking for is :

    foreach (var config in ConfigClasses)
    {
        modelBuilder.ApplyConfiguration(config);
    }

So the question is how can i get all of config classes ? i tried this but not working :

        var type = typeof(IEntityTypeConfiguration<Anytype : BaseModel>);
        var ConfigClasses= AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(p => type.IsAssignableFrom(p)).ToList();

problem is IEntityTypeConfiguration<Anytype : BaseModel> any idia how can i do this? in this way or any other way?

CodePudding user response:

There is a method on ModelBuilder for add all configurations and you can use it:

modelBuilder.ApplyConfigurationsFromAssembly(typeof(YourDbContext).Assembly);

As you know by this way the YourDbContext and the configurations must be in the same assembly.

CodePudding user response:

Here is an example on how to find generic interfaces via reflection:

var appDomain = AppDomain.CurrentDomain;
var assemblies = appDomain.GetAssemblies();

foreach (var assembly in assemblies)
{
    var types = assembly.GetTypes();

    foreach (var type in types)
    {
        var interfaces = type.GetInterfaces();

        foreach (var iface in interfaces)
        {
            if (iface.IsGenericType)
            {
                var genericInterface = iface.GetGenericTypeDefinition();

                if(genericInterface == typeof(MyGenericInterface<>))
                {
                    Console.WriteLine($"Type {type.Name} implements {genericInterface.Name}");
                }
            }
        }
    }
}

With this sketch you should be able to find all needed types, initialize them via Activator.CreateInstance() and apply these instances to your model builder.

  • Related