How to add DBContext to services from another assembly

asp.net-core c# entity-framework-core reflection

Question

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

1
0
4/15/2020 9:53:13 AM

Popular Answer

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);
0
4/15/2020 11:19:32 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow