.NET Core中批量注册上下文

1.定义一个静态类HostBuilderExtend作为扩展

 1 public static class HostBuilderExtend
 2     {
 3         public static void Register(this WebApplicationBuilder builder)
 4         {
11 
12             #region 配置数据库
13             List<Assembly> assemblyList = new List<Assembly>();
14             assemblyList.Add(Assembly.Load("上下文程序集"));
15             builder.Services.AddAllDbContexts(options =>
16             {
17                 options.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionString"));
18                 //将SQL语句输入到控制台
19                 options.LogTo(Console.WriteLine);
20             }, assemblyList);
21             #endregion
42         }
43 
44         /// <summary>
45         /// 注册所有数据库上下文
46         /// </summary>
47         /// <param name="services">服务容器</param>
48         /// <param name="options">数据库上下文配置</param>
49         /// <param name="assemblies">程序集</param>
50         /// <returns></returns>
51         public static void AddAllDbContexts(this IServiceCollection services,
52             Action<DbContextOptionsBuilder>options,
53             List<Assembly>assemblies)
54         {
55             //AddDbContext方法的参数类型
56             Type[] types = new Type[] {typeof(IServiceCollection),
57             typeof(Action<DbContextOptionsBuilder>),
58             typeof(ServiceLifetime),typeof(ServiceLifetime)};
59             //获得AddDbContext方法
60             var methodAddDbContext = typeof(EntityFrameworkServiceCollectionExtensions)
61                 .GetMethod("AddDbContext", 1, types);
62             foreach (var asmToLoad in assemblies)
63             {
64                 //获取所有继承自DbContext的类
65                 foreach(var dbCtxType in asmToLoad.GetTypes().Where(m=>!m.IsAbstract&&typeof(DbContext).IsAssignableFrom(m)))
66                 {
67                     var methodGenericAddDbContext=methodAddDbContext.MakeGenericMethod(dbCtxType);
68                     methodGenericAddDbContext.Invoke(null, new object[]
69                     {
70                         services,options,ServiceLifetime.Scoped,ServiceLifetime.Scoped,
71                     });
72                 }
73             }
74         }
75     }

2.在Program类中使用Register方法

var builder = WebApplication.CreateBuilder(args);
builder.Register();
posted @ 2023-02-19 22:41  守护月亮的星星  阅读(153)  评论(0)    收藏  举报