mirror of
https://github.com/nsnail/FreeSql.git
synced 2025-06-19 04:18:16 +08:00
- 优化 FreeSql.DbContext 构造方法,方便注入使用;
This commit is contained in:
@ -54,13 +54,19 @@ namespace FreeSql
|
||||
}
|
||||
#endregion
|
||||
|
||||
protected DbContext()
|
||||
protected DbContext() : this(null, null) { }
|
||||
protected DbContext(IFreeSql fsql, DbContextOptions options)
|
||||
{
|
||||
var builder = new DbContextOptionsBuilder();
|
||||
OnConfiguring(builder);
|
||||
_ormPriv = builder._fsql;
|
||||
_optionsPriv = builder._options;
|
||||
_ormPriv = fsql;
|
||||
_optionsPriv = options;
|
||||
|
||||
if (_ormPriv == null)
|
||||
{
|
||||
var builder = new DbContextOptionsBuilder();
|
||||
OnConfiguring(builder);
|
||||
_ormPriv = builder._fsql;
|
||||
_optionsPriv = builder._options;
|
||||
}
|
||||
if (_ormPriv != null) InitPropSets();
|
||||
}
|
||||
protected virtual void OnConfiguring(DbContextOptionsBuilder builder) { }
|
||||
|
@ -12,7 +12,17 @@ namespace FreeSql
|
||||
{
|
||||
services.AddScoped(dbContextType, sp =>
|
||||
{
|
||||
var ctx = Activator.CreateInstance(dbContextType) as DbContext;
|
||||
DbContext ctx = null;
|
||||
try
|
||||
{
|
||||
var ctor = dbContextType.GetConstructors().FirstOrDefault();
|
||||
var ctorParams = ctor.GetParameters().Select(a => sp.GetService(a.ParameterType)).ToArray();
|
||||
ctx = Activator.CreateInstance(dbContextType, ctorParams) as DbContext;
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
throw new Exception($"AddFreeDbContext 发生错误,请检查 {dbContextType.Name} 的构造参数都已正确注入", ex);
|
||||
}
|
||||
if (ctx != null && ctx._ormPriv == null)
|
||||
{
|
||||
var builder = new DbContextOptionsBuilder();
|
||||
|
Reference in New Issue
Block a user