添加项目文件。
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user