2

on .net core 2.1, I have loaded the assembly to the application using

services.AddMvcCore().AddApplicationPart([Assembly])

But the assembly contains its DB context , the problem is that I am not able to load the DBContext from the assembly, in a similar way of loading the controllers. Typically we add the DB Context using

services.AddDbContext<[DBCOntextType]>([options]);

I cannot get to pass the type to this function (AddDBContext) using reflection as follow :

 System.Reflection.MethodInfo method = services.GetType().GetMethod("AddDbContext",System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);

method variable is always null.

Also if the assembly contains a startup.cs file I am not able to run this startup along with the startup of the main app.

Please let me know if there is a solution Thanks

Mosta
  • 868
  • 10
  • 23
  • Does this answer your question? [How do I use reflection to call a generic method?](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) – thehennyy Apr 15 '20 at 06:45
  • @thehennyy I have updated the question with the reflection code that does not work – Mosta Apr 15 '20 at 09:55
  • 1
    `AddDbContext` seems to be an extension method, so it is not present in the type of `services` but somewhere else. Most likely the method is defined in `EntityFrameworkServiceCollectionExtensions`. – thehennyy Apr 15 '20 at 10:12
  • @thehennyy Thanks yes, it was the reflection solution that needed to be fixed – Mosta Apr 15 '20 at 11:10

1 Answers1

1

The solution was the reflection solution as @thehenny directed me to the right direction

Here is the code assuming that you already loaded the type dbContextType from assembly

var type = typeof (Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions);
                System.Reflection.MethodInfo method = type.GetMethods().Where(i=>i.Name  == "AddDbContext" 
                && i.IsGenericMethod==true).FirstOrDefault();

System.Reflection.MethodInfo generic = method.MakeGenericMethod(dbContextType);

Action<DbContextOptionsBuilder> action = new Action<DbContextOptionsBuilder>(options =>[Your Options]);
object[] parametersArray = new object[] { services, action,null,null };
generic.Invoke(services, parametersArray);
Mosta
  • 868
  • 10
  • 23