yubaolee 2021-04-21 18:02:01 +08:00
parent d4894b5ba3
commit b278a1ec10
19 changed files with 124 additions and 65 deletions

View File

@ -1,4 +1,6 @@
namespace Infrastructure using System.Collections.Generic;
namespace Infrastructure
{ {
/// <summary> /// <summary>
/// 配置项 /// 配置项
@ -12,7 +14,6 @@
Version = ""; Version = "";
UploadPath = ""; UploadPath = "";
IdentityServerUrl = ""; IdentityServerUrl = "";
DbType = Define.DBTYPE_SQLSERVER;
} }
/// <summary> /// <summary>
/// SSO地址 /// SSO地址
@ -28,7 +29,7 @@
/// <summary> /// <summary>
/// 数据库类型 SqlServer、MySql /// 数据库类型 SqlServer、MySql
/// </summary> /// </summary>
public string DbType { get; set; } public Dictionary<string, string> DbTypes { get; set; }
/// <summary> 附件上传路径</summary> /// <summary> 附件上传路径</summary>
public string UploadPath { get; set; } public string UploadPath { get; set; }

View File

@ -1,13 +0,0 @@
using Infrastructure.Extensions.AutofacManager;
using Microsoft.AspNetCore.Http;
namespace Infrastructure.Utilities
{
public static class HttpContext
{
private static IHttpContextAccessor _accessor=AutofacContainerModule.GetService<IHttpContextAccessor>();
public static Microsoft.AspNetCore.Http.HttpContext Current => _accessor.HttpContext;
}
}

View File

@ -0,0 +1,40 @@
using Infrastructure.Extensions.AutofacManager;
using Microsoft.AspNetCore.Http;
namespace Infrastructure.Utilities
{
public static class HttpContextUtil
{
private static IHttpContextAccessor _accessor=AutofacContainerModule.GetService<IHttpContextAccessor>();
public static Microsoft.AspNetCore.Http.HttpContext Current => _accessor.HttpContext;
/// <summary>
/// 获取租户ID
/// </summary>
/// <returns></returns>
public static string GetTenantId(this IHttpContextAccessor accessor)
{
string tenantId = "OpenAuthDBContext";
if (accessor != null && accessor.HttpContext != null)
{
//读取多租户ID
var httpTenantId = accessor.HttpContext.Request.Query[Define.TENANT_ID];
if (string.IsNullOrEmpty(httpTenantId))
{
httpTenantId = accessor.HttpContext.Request.Headers[Define.TENANT_ID];
}
//如果没有租户id或租户用的是默认的OpenAuthDBContext,则不做任何调整
if (!string.IsNullOrEmpty(httpTenantId))
{
tenantId = httpTenantId;
}
}
return tenantId;
}
}
}

View File

@ -499,11 +499,6 @@ namespace OpenAuth.App
FileHelper.RegxAddContentByParenthesis(openAuthDBContextPath, "public virtual DbSet<" + tableInfo.ClassName + "> " + tableInfo.TableName + "s { get; set; }"); FileHelper.RegxAddContentByParenthesis(openAuthDBContextPath, "public virtual DbSet<" + tableInfo.ClassName + "> " + tableInfo.TableName + "s { get; set; }");
} }
private bool IsMysql()
{
return (_appConfiguration.Value.DbType == Define.DBTYPE_MYSQL);
}
Dictionary<string, Type> PrimitiveTypes = new Dictionary<string, Type>() Dictionary<string, Type> PrimitiveTypes = new Dictionary<string, Type>()
{ {
{"int", typeof(int)} {"int", typeof(int)}

View File

@ -5,6 +5,8 @@ using System.Data;
using System.Linq; using System.Linq;
using Autofac.Extensions.DependencyInjection; using Autofac.Extensions.DependencyInjection;
using Infrastructure; using Infrastructure;
using Infrastructure.Utilities;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Internal;
@ -22,10 +24,12 @@ namespace OpenAuth.App
private List<DbContext> _contexts = new List<DbContext>(); private List<DbContext> _contexts = new List<DbContext>();
private IOptions<AppSetting> _appConfiguration; private IOptions<AppSetting> _appConfiguration;
private IHttpContextAccessor _httpContextAccessor;
public DbExtension(IOptions<AppSetting> appConfiguration, OpenAuthDBContext openAuthDbContext) public DbExtension(IOptions<AppSetting> appConfiguration, OpenAuthDBContext openAuthDbContext, IHttpContextAccessor httpContextAccessor)
{ {
_appConfiguration = appConfiguration; _appConfiguration = appConfiguration;
_httpContextAccessor = httpContextAccessor;
_contexts.Add(openAuthDbContext); //如果有多个DBContext可以按OpenAuthDBContext同样的方式添加到_contexts中 _contexts.Add(openAuthDbContext); //如果有多个DBContext可以按OpenAuthDBContext同样的方式添加到_contexts中
} }
@ -105,7 +109,8 @@ namespace OpenAuth.App
/// <returns></returns> /// <returns></returns>
public IList<SysTableColumn> GetDbTableStructure(string tableName) public IList<SysTableColumn> GetDbTableStructure(string tableName)
{ {
if (_appConfiguration.Value.DbType == Define.DBTYPE_MYSQL) var dbtype = _appConfiguration.Value.DbTypes[_httpContextAccessor.GetTenantId()];
if (dbtype == Define.DBTYPE_MYSQL)
{ {
return GetMySqlStructure(tableName); return GetMySqlStructure(tableName);
} }

View File

@ -2,6 +2,8 @@ using System;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Infrastructure; using Infrastructure;
using Infrastructure.Utilities;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using OpenAuth.App.Interface; using OpenAuth.App.Interface;
using OpenAuth.App.Request; using OpenAuth.App.Request;
@ -17,6 +19,7 @@ namespace OpenAuth.App
{ {
private IAuth _auth; private IAuth _auth;
private IOptions<AppSetting> _appConfiguration; private IOptions<AppSetting> _appConfiguration;
private IHttpContextAccessor _httpContextAccessor;
/// <summary> /// <summary>
/// 加载列表 /// 加载列表
/// </summary> /// </summary>
@ -44,7 +47,9 @@ namespace OpenAuth.App
UnitWork.Add(obj); UnitWork.Add(obj);
if (!string.IsNullOrEmpty(obj.DbName)) if (!string.IsNullOrEmpty(obj.DbName))
{ {
UnitWork.ExecuteSql(FormUtil.GetSql(obj, _appConfiguration.Value.DbType)); var dbtype = _appConfiguration.Value.DbTypes[_httpContextAccessor.GetTenantId()];
UnitWork.ExecuteSql(FormUtil.GetSql(obj, dbtype));
} }
UnitWork.Save(); UnitWork.Save();
} }
@ -67,7 +72,8 @@ namespace OpenAuth.App
if (!string.IsNullOrEmpty(obj.DbName)) if (!string.IsNullOrEmpty(obj.DbName))
{ {
UnitWork.ExecuteSql(FormUtil.GetSql(obj, _appConfiguration.Value.DbType)); var dbtype = _appConfiguration.Value.DbTypes[_httpContextAccessor.GetTenantId()];
UnitWork.ExecuteSql(FormUtil.GetSql(obj, dbtype));
} }
} }
@ -78,10 +84,11 @@ namespace OpenAuth.App
} }
public FormApp(IUnitWork<OpenAuthDBContext> unitWork, IRepository<Form,OpenAuthDBContext> repository, public FormApp(IUnitWork<OpenAuthDBContext> unitWork, IRepository<Form,OpenAuthDBContext> repository,
IAuth auth, IOptions<AppSetting> appConfiguration) : base(unitWork, repository, auth) IAuth auth, IOptions<AppSetting> appConfiguration, IHttpContextAccessor httpContextAccessor) : base(unitWork, repository, auth)
{ {
_auth = auth; _auth = auth;
_appConfiguration = appConfiguration; _appConfiguration = appConfiguration;
_httpContextAccessor = httpContextAccessor;
} }
} }
} }

View File

@ -1,8 +1,10 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq;
using Autofac.Extensions.DependencyInjection; using Autofac.Extensions.DependencyInjection;
using Infrastructure; using Infrastructure;
using Infrastructure.Extensions.AutofacManager; using Infrastructure.Extensions.AutofacManager;
using Infrastructure.Utilities;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -33,8 +35,7 @@ namespace OpenAuth.App.Test
.AddJsonFile("appsettings.Development.json", optional: true) .AddJsonFile("appsettings.Development.json", optional: true)
.AddEnvironmentVariables() .AddEnvironmentVariables()
.Build(); .Build();
Console.WriteLine($"单元测试数据库信息:{config.GetSection("AppSetting")["DbType"]}/{config.GetSection("ConnectionStrings")["OpenAuthDBContext"]}");
serviceCollection.Configure<AppSetting>(config.GetSection("AppSetting")); serviceCollection.Configure<AppSetting>(config.GetSection("AppSetting"));
//添加log4net //添加log4net
serviceCollection.AddLogging(builder => serviceCollection.AddLogging(builder =>
@ -57,6 +58,12 @@ namespace OpenAuth.App.Test
var container = AutofacExt.InitForTest(serviceCollection); var container = AutofacExt.InitForTest(serviceCollection);
_autofacServiceProvider = new AutofacServiceProvider(container); _autofacServiceProvider = new AutofacServiceProvider(container);
AutofacContainerModule.ConfigServiceProvider(_autofacServiceProvider); AutofacContainerModule.ConfigServiceProvider(_autofacServiceProvider);
var dbtypes = config.GetSection("AppSetting:DbTypes").GetChildren()
.ToDictionary(x => x.Key, x => x.Value);
Console.WriteLine($"单元测试数据库信息:{dbtypes[httpContextAccessorMock.Object.GetTenantId()]}/{config.GetSection("ConnectionStrings")["OpenAuthDBContext"]}");
} }
/// <summary> /// <summary>

View File

@ -12,7 +12,6 @@ using Microsoft.Extensions.Hosting;
using Moq; using Moq;
using OpenAuth.App.Request; using OpenAuth.App.Request;
using OpenAuth.App.SSO; using OpenAuth.App.SSO;
using HttpContext = Infrastructure.Utilities.HttpContext;
namespace OpenAuth.App.Test namespace OpenAuth.App.Test
{ {

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Linq;
using Autofac; using Autofac;
using Infrastructure; using Infrastructure;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
@ -69,9 +70,11 @@ namespace OpenAuth.IdentityServer
//映射配置文件 //映射配置文件
services.Configure<AppSetting>(Configuration.GetSection("AppSetting")); services.Configure<AppSetting>(Configuration.GetSection("AppSetting"));
//在startup里面只能通过这种方式获取到appsettings里面的值不能用IOptions😰 //在startup里面只能通过这种方式获取到appsettings里面的值不能用IOptions😰
var dbType = ((ConfigurationSection) Configuration.GetSection("AppSetting:DbType")).Value; var dbtypes = ((ConfigurationSection)Configuration.GetSection("AppSetting:DbTypes")).GetChildren()
.ToDictionary(x => x.Key, x => x.Value);
var dbType = dbtypes["OpenAuthDBContext"];
if (dbType == Define.DBTYPE_SQLSERVER) if (dbType == Define.DBTYPE_SQLSERVER)
{ {
services.AddDbContext<OpenAuthDBContext>(options => services.AddDbContext<OpenAuthDBContext>(options =>

View File

@ -9,6 +9,8 @@
"OpenAuthDBContext": "server=127.0.0.1;user id=root;database=openauthdb;password=000000" //my sql "OpenAuthDBContext": "server=127.0.0.1;user id=root;database=openauthdb;password=000000" //my sql
}, },
"AppSetting": { "AppSetting": {
"DbType": "MySql" //SqlServer/MySql "DbTypes": {
"OpenAuthDBContext":"MySql" //SqlServerMySqlOracle
}
} }
} }

View File

@ -10,6 +10,8 @@
//"OpenAuthDBContext": "server=127.0.0.1;user id=root;database=openauthdb;password=000000" //my sql //"OpenAuthDBContext": "server=127.0.0.1;user id=root;database=openauthdb;password=000000" //my sql
}, },
"AppSetting": { "AppSetting": {
"DbType": "SqlServer" //SqlServer/MySql "DbTypes": {
"OpenAuthDBContext":"SqlServer" //SqlServerMySqlOracle
}
} }
} }

View File

@ -1,4 +1,5 @@
using System.IO; using System.IO;
using System.Linq;
using Autofac; using Autofac;
using Infrastructure; using Infrastructure;
using Infrastructure.Extensions.AutofacManager; using Infrastructure.Extensions.AutofacManager;
@ -88,9 +89,10 @@ namespace OpenAuth.Mvc
services.Configure<AppSetting>(Configuration.GetSection("AppSetting")); services.Configure<AppSetting>(Configuration.GetSection("AppSetting"));
//在startup里面只能通过这种方式获取到appsettings里面的值不能用IOptions😰 //在startup里面只能通过这种方式获取到appsettings里面的值不能用IOptions😰
var dbType = ((ConfigurationSection)Configuration.GetSection("AppSetting:DbType")).Value; var dbtypes = ((ConfigurationSection)Configuration.GetSection("AppSetting:DbTypes")).GetChildren()
.ToDictionary(x => x.Key, x => x.Value);
var connectionString = Configuration.GetConnectionString("OpenAuthDBContext"); var connectionString = Configuration.GetConnectionString("OpenAuthDBContext");
logger.LogInformation($"当前数据库类型:{dbType},连接字符串:{connectionString}"); logger.LogInformation($"系统配置的数据库类型:{JsonHelper.Instance.Serialize(dbtypes)},连接字符串:{connectionString}");
services.AddDbContext<OpenAuthDBContext>(); services.AddDbContext<OpenAuthDBContext>();

View File

@ -13,7 +13,9 @@
"IdentityServerUrl": "http://demo.openauth.me:12796", //IdentityServerOAuth "IdentityServerUrl": "http://demo.openauth.me:12796", //IdentityServerOAuth
// "IdentityServerUrl": "", //IdentityServerOAuth // "IdentityServerUrl": "", //IdentityServerOAuth
"SSOPassport": "http://localhost:52789", "SSOPassport": "http://localhost:52789",
"Version": "demo", "Version": "demo",
"DbType": "MySql" // SqlServer/MySql "DbTypes": {
"OpenAuthDBContext":"MySql" //SqlServerMySqlOracle
}
} }
} }

View File

@ -15,6 +15,8 @@
"IdentityServerUrl": "", //IdentityServerOAuth "IdentityServerUrl": "", //IdentityServerOAuth
"SSOPassport": "http://localhost:52789", "SSOPassport": "http://localhost:52789",
"Version": "1.0", //demopost "Version": "1.0", //demopost
"DbType": "SqlServer" //SqlServerMySql "DbTypes": {
"OpenAuthDBContext":"SqlServer" //SqlServerMySqlOracle
}
} }
} }

View File

@ -1,5 +1,9 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using Infrastructure; using Infrastructure;
using Infrastructure.Extensions;
using Infrastructure.Utilities;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -40,24 +44,8 @@ namespace OpenAuth.Repository
//初始化多租户信息根据租户id调整数据库 //初始化多租户信息根据租户id调整数据库
private void InitTenant(DbContextOptionsBuilder optionsBuilder) private void InitTenant(DbContextOptionsBuilder optionsBuilder)
{ {
string tenantId = "OpenAuthDBContext";
var tenantId = _httpContextAccessor.GetTenantId();
if (_httpContextAccessor != null && _httpContextAccessor.HttpContext != null)
{
//读取多租户ID
var httpTenantId = _httpContextAccessor.HttpContext.Request.Query[Define.TENANT_ID];
if (string.IsNullOrEmpty(httpTenantId))
{
httpTenantId = _httpContextAccessor.HttpContext.Request.Headers[Define.TENANT_ID];
}
//如果没有租户id或租户用的是默认的OpenAuthDBContext,则不做任何调整
if (!string.IsNullOrEmpty(httpTenantId))
{
tenantId = httpTenantId;
}
}
string connect = _configuration.GetConnectionString(tenantId); string connect = _configuration.GetConnectionString(tenantId);
if (string.IsNullOrEmpty(connect)) if (string.IsNullOrEmpty(connect))
{ {
@ -65,7 +53,10 @@ namespace OpenAuth.Repository
} }
//这个地方如果用IOption在单元测试的时候会获取不到AppSetting的值😅 //这个地方如果用IOption在单元测试的时候会获取不到AppSetting的值😅
var dbType = _configuration.GetSection("AppSetting")["DbType"]; var dbtypes = _configuration.GetSection("AppSetting:DbTypes").GetChildren()
.ToDictionary(x => x.Key, x => x.Value);
var dbType = dbtypes[tenantId];
if (dbType == Define.DBTYPE_SQLSERVER) if (dbType == Define.DBTYPE_SQLSERVER)
{ {
optionsBuilder.UseSqlServer(connect); optionsBuilder.UseSqlServer(connect);

View File

@ -1,9 +1,11 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq;
using System.Reflection; using System.Reflection;
using Autofac; using Autofac;
using Autofac.Extensions.DependencyInjection; using Autofac.Extensions.DependencyInjection;
using Infrastructure; using Infrastructure;
using Infrastructure.Utilities;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -45,8 +47,7 @@ namespace OpenAuth.Repository.Test
.AddJsonFile("appsettings.Development.json", optional: true) .AddJsonFile("appsettings.Development.json", optional: true)
.AddEnvironmentVariables() .AddEnvironmentVariables()
.Build(); .Build();
Console.WriteLine($"单元测试数据库信息:{config.GetSection("AppSetting")["DbType"]}/{config.GetSection("ConnectionStrings")["OpenAuthDBContext"]}");
//添加log4net //添加log4net
serviceCollection.AddLogging(builder => serviceCollection.AddLogging(builder =>
{ {
@ -74,6 +75,12 @@ namespace OpenAuth.Repository.Test
var _container = builder.Build(); var _container = builder.Build();
_autofacServiceProvider = new AutofacServiceProvider(_container); _autofacServiceProvider = new AutofacServiceProvider(_container);
var dbtypes = config.GetSection("AppSetting:DbTypes").GetChildren()
.ToDictionary(x => x.Key, x => x.Value);
Console.WriteLine($"单元测试数据库信息:{dbtypes[httpContextAccessorMock.Object.GetTenantId()]}/{config.GetSection("ConnectionStrings")["OpenAuthDBContext"]}");
} }

View File

@ -140,9 +140,10 @@ namespace OpenAuth.WebApi
// policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins(origins))); // policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins(origins)));
//在startup里面只能通过这种方式获取到appsettings里面的值不能用IOptions😰 //在startup里面只能通过这种方式获取到appsettings里面的值不能用IOptions😰
var dbType = ((ConfigurationSection)Configuration.GetSection("AppSetting:DbType")).Value; var dbtypes = ((ConfigurationSection)Configuration.GetSection("AppSetting:DbTypes")).GetChildren()
.ToDictionary(x => x.Key, x => x.Value);
var connectionString = Configuration.GetConnectionString("OpenAuthDBContext"); var connectionString = Configuration.GetConnectionString("OpenAuthDBContext");
logger.LogInformation($"当前数据库类型:{dbType},连接字符串:{connectionString}"); logger.LogInformation($"系统配置的数据库类型:{JsonHelper.Instance.Serialize(dbtypes)},连接字符串:{connectionString}");
services.AddDbContext<OpenAuthDBContext>(); services.AddDbContext<OpenAuthDBContext>();
services.AddHttpClient(); services.AddHttpClient();

View File

@ -14,7 +14,9 @@
"AppSetting": { "AppSetting": {
"IdentityServerUrl": "", //IdentityServerOAuth "IdentityServerUrl": "", //IdentityServerOAuth
//"IdentityServerUrl": "http://demo.openauth.me:12796", //IdentityServerOAuth //"IdentityServerUrl": "http://demo.openauth.me:12796", //IdentityServerOAuth
"DbType": "MySql", //SqlServerMySqlOracle "DbTypes": {
"OpenAuthDBContext":"MySql" //SqlServerMySqlOracle
},
"UploadPath": "", // "UploadPath": "", //
"RedisConf": "your_redis_server:6379,password=your_redis_password" //redis "RedisConf": "your_redis_server:6379,password=your_redis_password" //redis
} }

View File

@ -8,13 +8,17 @@
"DataProtection": "temp-keys/", "DataProtection": "temp-keys/",
"ConnectionStrings": { "ConnectionStrings": {
"OpenAuthDBContext": "Data Source=.;Initial Catalog=OpenAuthDB;User=sa;Password=000000" "OpenAuthDBContext": "Data Source=.;Initial Catalog=OpenAuthDB;User=sa;Password=000000"
//"OpenAuthDBContext": "DATA SOURCE=192.168.0.118:1521/YUBAO;PASSWORD=000000;Validate Connection=true;PERSIST SECURITY INFO=True;USER ID=yubaolee;" //Oracle //"OpenAuthDBContext2": "DATA SOURCE=192.168.0.118:1521/YUBAO;PASSWORD=000000;Validate Connection=true;PERSIST SECURITY INFO=True;USER ID=yubaolee;" //Oracle
//"OpenAuthDBContext": "server=127.0.0.1;user id=root;database=openauthdb;password=000000" //my sql //"OpenAuthDBContext3": "server=127.0.0.1;user id=root;database=openauthpro;password=000000" //my sql
}, },
"AppSetting": { "AppSetting": {
"IdentityServerUrl": "", //IdentityServerOAuth "IdentityServerUrl": "", //IdentityServerOAuth
// "IdentityServerUrl": "http://localhost:12796", //IdentityServerOAuth // "IdentityServerUrl": "http://localhost:12796", //IdentityServerOAuth
"DbType": "SqlServer", //SqlServerMySqlOracle "DbTypes": {
"OpenAuthDBContext":"SqlServer" //SqlServerMySqlOracle
// ,"OpenAuthDBContext2":"Oracle"
// ,"OpenAuthDBContext3":"MySql"
},
"UploadPath": "", // "UploadPath": "", //
"RedisConf": "redistest.cq-p.com.cn:8001,password=share_redis@123" "RedisConf": "redistest.cq-p.com.cn:8001,password=share_redis@123"
} }