I have an extesion method with the following signature
public static void AddConfiguration<TEntity>(this ModelBuilder builder, EntityTypeConfiguration<TEntity> configuration)
where TEntity : class
{
...
}
I want to pass the parameter via Reflection and tried this method:
var ctors = type.GetConstructors(BindingFlags.Public);
modelBuilder.AddConfiguration(ctors[0].Invoke(new object[] { }));
And this way:
modelBuilder.AddConfiguration(Activator.CreateInstance(type));
The classes I'm getting from reflection are like these:
public class LessonMapping : EntityTypeConfiguration<Lesson>
public class ChapterMapping : EntityTypeConfiguration<Chapter>
public class TrainingMapping : EntityTypeConfiguration<Training>
Both return an object
so the method does not accept them. Is there any way to do that?
Activator
has a generic method for creating typed instances that have a default constructor. By the looks of it you have that, so use the following:If that doesn't work for you or you need to pass arguments to your constructors:
Finally if you are putting this code inside another generic method you would replace LessonMapping etc with a generic:
EDIT add reflection of AddConfiguration method
For a non-generic usage of your AddConfiguration method you will have to use reflection to invoke it:
My assumptions at this point are:
entityType
toentityConfigType
and remove the first line which makes the generic type. See below for type checking code that should replace that first line.Extensions
.AddConfiguration(...)
so you don't get invocation exceptions due to bad types being used. Again see below for an example of the type check I would typically add to such a non-generic method.methodDef
works as expected because I don't have means to test it at the moment.If you are passing the
entityConfigType
directly and want to check the type then add this in the first few lines:And create the check method somewhere. I'm sure there must be an easier way to test if a type derives from a given generic definition but I use this all the time until I get shown the easier way.