【问题标题】:How to add DBContext to services from another assembly如何从另一个程序集将 DBContext 添加到服务
【发布时间】:2020-04-15 00:14:03
【问题描述】:

在 .net 核心 2.1 上, 我已使用

将程序集加载到应用程序
services.AddMvcCore().AddApplicationPart([Assembly])

但是程序集包含它的数据库上下文,问题是 我无法以加载控制器的类似方式从程序集中加载 DBContext。 通常我们使用

添加数据库上下文
services.AddDbContext<[DBCOntextType]>([options]);

我无法使用反射将类型传递给此函数(AddDBContext),如下所示:

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

方法变量始终为空。

此外,如果程序集包含 startup.cs 文件,我将无法在主应用程序启动的同时运行此启动。

如果有解决办法请告诉我 谢谢

【问题讨论】:

  • 这能回答你的问题吗? How do I use reflection to call a generic method?
  • @thehennyy 我已经用不起作用的反射代码更新了问题
  • AddDbContext 似乎是一种扩展方法,因此它不存在于services 的类型中,而是存在于其他地方。该方法很可能是在EntityFrameworkServiceCollectionExtensions 中定义的。
  • @thehennyy 谢谢,是的,需要修复的是反射解决方案

标签: c# asp.net-core reflection entity-framework-core


【解决方案1】:

解决方案是反射解决方案,因为@thehenny 将我引导到正确的方向

这是假设您已经从程序集中加载了类型 dbContextType 的代码

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);

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    相关资源
    最近更新 更多