FreeSql/FreeSql.DbContext/Extensions/DependencyInjection.cs
28810 d5ed1c8a30 - 优化 实体基类的属性位置,优先排在最前面; #164
- 整理 实体类 Ctor 有构造函数的映射处理;#164 [wiki](https://github.com/2881099/FreeSql/wiki/%e8%bf%94%e5%9b%9e%e6%95%b0%e6%8d%ae#dto-%E6%98%A0%E5%B0%84%E6%9F%A5%E8%AF%A2)
- 优化 实体属性,支持 protected set 属性;#164
2019-12-22 20:10:21 +08:00

56 lines
2.3 KiB
C#

#if ns20
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Reflection;
namespace FreeSql
{
public static class DbContextDependencyInjection
{
static IServiceCollection AddFreeDbContext(this IServiceCollection services, Type dbContextType, Action<DbContextOptionsBuilder> options)
{
services.AddScoped(dbContextType, sp =>
{
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();
options(builder);
ctx._ormPriv = builder._fsql;
ctx._optionsPriv = builder._options;
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;
}
}
}
#endif