招聘后台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

101 lines
3.6 KiB

using Microsoft.Extensions.DependencyInjection;
using Znyc.Recruitment.Admin.Commons.Core.DataManager;
using Znyc.Recruitment.Admin.Commons.DataManager;
using Znyc.Recruitment.Admin.Commons.Extensions;
using Znyc.Recruitment.Admin.Commons.IDbContext;
using Znyc.Recruitment.Admin.Commons.Options;
namespace Znyc.Recruitment.Admin.Commons.DbContextCore
{
/// <summary>
/// 上下文工厂类
/// </summary>
public class DbContextFactory : IDbContextFactory
{
/// <summary>
/// </summary>
public static DbContextFactory Instance => new();
/// <summary>
/// 服务
/// </summary>
public IServiceCollection ServiceCollection { get; set; }
/// <summary>
/// 创建数据库读写上下文
/// </summary>
/// <param name="writeAndRead">指定读、写操作</param>
/// <returns></returns>
public BaseDbContext CreateContext(WriteAndReadEnum writeAndRead)
{
DbConnectionOptions dbConnectionOptions = new DbConnectionOptions();
switch (writeAndRead)
{
case WriteAndReadEnum.Write:
dbConnectionOptions = DBServerProvider.GeDbConnectionOptions();
break;
case WriteAndReadEnum.Read:
dbConnectionOptions = DBServerProvider.GeDbConnectionOptions(false);
break;
default:
dbConnectionOptions = DBServerProvider.GeDbConnectionOptions();
break;
}
return new BaseDbContext(dbConnectionOptions);
}
/// <summary>
/// 创建数据库读写上下文
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="writeAndRead">指定读、写操作</param>
/// <returns></returns>
public BaseDbContext CreateContext<TEntity>(WriteAndReadEnum writeAndRead)
{
DbConnectionOptions dbConnectionOptions = new DbConnectionOptions();
switch (writeAndRead)
{
case WriteAndReadEnum.Write:
dbConnectionOptions = DBServerProvider.GeDbConnectionOptions<TEntity>();
break;
case WriteAndReadEnum.Read:
dbConnectionOptions = DBServerProvider.GeDbConnectionOptions<TEntity>(false);
break;
default:
dbConnectionOptions = DBServerProvider.GeDbConnectionOptions<TEntity>();
break;
}
return new BaseDbContext(dbConnectionOptions);
}
/// <summary>
/// 向服务注入上下文
/// </summary>
/// <typeparam name="TContext"></typeparam>
/// <param name="option"></param>
public void AddDbContext<TContext>(DbContextOption option)
where TContext : BaseDbContext, IDbContextCore
{
ServiceCollection.AddDbContext<IDbContextCore, TContext>(option);
}
/// <summary>
/// 向服务注入上下文
/// </summary>
/// <typeparam name="ITContext">上下文接口</typeparam>
/// <typeparam name="TContext">上下文实现类</typeparam>
/// <param name="option"></param>
public void AddDbContext<ITContext, TContext>(DbContextOption option)
where ITContext : IDbContextCore
where TContext : BaseDbContext, ITContext
{
ServiceCollection.AddDbContext<ITContext, TContext>(option);
}
}
}