- 优化 DbContext/Repository 局部调整;

This commit is contained in:
28810
2019-08-13 19:13:48 +08:00
parent 79ab3ae217
commit a79ee52b4f
14 changed files with 211 additions and 197 deletions

View File

@ -1,35 +1,44 @@
#if ns20
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Reflection;
namespace FreeSql
{
public static class DbContextDependencyInjection
{
public static IServiceCollection AddFreeDbContext<TDbContext>(this IServiceCollection services, Action<DbContextOptionsBuilder> options) where TDbContext : DbContext
static IServiceCollection AddFreeDbContext(this IServiceCollection services, Type dbContextType, Action<DbContextOptionsBuilder> options)
{
services.AddScoped<TDbContext>(sp =>
services.AddScoped(dbContextType, sp =>
{
var ctx = Activator.CreateInstance<TDbContext>();
if (ctx._orm == null)
var ctx = Activator.CreateInstance(dbContextType) as DbContext;
if (ctx != null && ctx._ormPriv == null)
{
var builder = new DbContextOptionsBuilder();
options(builder);
ctx._orm = builder._fsql;
ctx._ormPriv = builder._fsql;
ctx._optionsPriv = builder._options;
if (ctx._orm == null)
if (ctx._ormPriv == null)
throw new Exception("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");
ctx.InitPropSets();
}
return ctx;
});
return services;
}
public static IServiceCollection AddFreeDbContext<TDbContext>(this IServiceCollection services, Action<DbContextOptionsBuilder> options) where TDbContext : DbContext =>
AddFreeDbContext(services, typeof(TDbContext), options);
public static IServiceCollection AddFreeDbContext(this IServiceCollection services, Action<DbContextOptionsBuilder> options, Assembly[] assemblies)
{
if (assemblies?.Any() == true)
foreach (var asse in assemblies)
foreach (var dbType in asse.GetTypes().Where(a => a.IsAbstract == false && typeof(DbContext).IsAssignableFrom(a)))
AddFreeDbContext(services, dbType, options);
return services;
}
}