BotSharp/src/Infrastructure/BotSharp.Core/Repository/DataContextHelper.cs

43 lines
1.5 KiB
C#
Raw Normal View History

2023-06-11 23:46:02 +00:00
using BotSharp.Core.Repository.Abstraction;
2023-06-03 02:07:30 +00:00
using EntityFrameworkCore.BootKit;
2023-06-11 23:46:02 +00:00
using Microsoft.Data.SqlClient;
2023-06-07 00:59:32 +00:00
using System.Data.Common;
2023-06-03 02:07:30 +00:00
namespace BotSharp.Core.Repository;
public static class DataContextHelper
{
public static T GetDbContext<T>(MyDatabaseSettings settings, IServiceProvider serviceProvider)
where T : Database, new()
{
if (settings.Assemblies == null)
throw new Exception("Please set assemblies.");
AppDomain.CurrentDomain.SetData("Assemblies", settings.Assemblies);
var dc = new T();
2023-06-07 00:59:32 +00:00
if (typeof(T) == typeof(MongoDbContext))
2023-06-03 02:07:30 +00:00
{
dc.BindDbContext<IMongoDbCollection, DbContext4MongoDb>(new DatabaseBind
{
ServiceProvider = serviceProvider,
2023-06-07 00:59:32 +00:00
MasterConnection = new MongoDbConnection(settings.MongoDb.Master),
IsRelational = false
2023-06-03 02:07:30 +00:00
});
}
2023-06-11 23:46:02 +00:00
else if (typeof(T) == typeof(AgentDbContext))
{
dc.BindDbContext<IAgentTable, DbContext4SqlServer2>(new DatabaseBind
{
ServiceProvider = serviceProvider,
MasterConnection = new SqlConnection(settings.BotSharp.Master),
SlaveConnections = settings.BotSharp.Slavers.Length == 0 ?
new List<DbConnection> { new SqlConnection(settings.BotSharp.Master) } :
settings.BotSharp.Slavers.Select(x => new SqlConnection(x) as DbConnection).ToList(),
2023-06-11 23:46:02 +00:00
CreateDbIfNotExist = true
});
}
2023-06-03 02:07:30 +00:00
return dc;
}
}