- 优化 FreeSql.DbContext 构造方法,方便注入使用;

This commit is contained in:
28810
2019-10-23 12:32:47 +08:00
parent aaed0334b8
commit cb55f51413
4 changed files with 47 additions and 27 deletions

View File

@ -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) { }

View File

@ -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();