35 lines
1.9 KiB
C#
35 lines
1.9 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using System.Reflection;
|
|
|
|
namespace IM.InitCommon
|
|
{
|
|
public static class AddDbContextExtensions
|
|
{
|
|
public static IServiceCollection AddAllDbContexts(this IServiceCollection services, Action<DbContextOptionsBuilder> action, IEnumerable<Assembly> assemblies)
|
|
{
|
|
//AddDbContextPool不支持DbContext注入其他对象,而且使用不当有内存暴涨的问题,因此不用AddDbContextPool
|
|
Type[] types = new Type[] { typeof(IServiceCollection), typeof(Action<DbContextOptionsBuilder>), typeof(ServiceLifetime), typeof(ServiceLifetime) };
|
|
var methodAddDbContext = typeof(EntityFrameworkServiceCollectionExtensions)
|
|
.GetMethod(nameof(EntityFrameworkServiceCollectionExtensions.AddDbContext), 1, types);
|
|
foreach (var asmToLoad in assemblies)
|
|
{
|
|
Type[] typesInAsm = asmToLoad.GetTypes();
|
|
//Register DbContext
|
|
//GetTypes() include public/protected ones
|
|
//GetExportedTypes only include public ones
|
|
//so that XXDbContext in Agrregation can be internal to keep insulated
|
|
foreach (var dbCtxType in typesInAsm
|
|
.Where(t => !t.IsAbstract && typeof(DbContext).IsAssignableFrom(t)))
|
|
{
|
|
//similar to serviceCollection.AddDbContextPool<ECDictDbContext>(opt=>new DbContextOptionsBuilder(dbCtxOpt));
|
|
var methodGenericAddDbContext = methodAddDbContext.MakeGenericMethod(dbCtxType);
|
|
methodGenericAddDbContext.Invoke(null, new object[] { services, action, ServiceLifetime.Scoped, ServiceLifetime.Scoped });
|
|
services.AddScoped(sp => new Management.ManagementDbProbe((DbContext)sp.GetRequiredService(dbCtxType)));
|
|
}
|
|
}
|
|
return services;
|
|
}
|
|
}
|
|
}
|