2021-03-20 14:12:24 +08:00
|
|
|
|
using CC.Yi.Model;
|
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
|
using System.Threading;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
namespace CC.Yi.DAL
|
|
|
|
|
|
{
|
|
|
|
|
|
public class DbContentFactory
|
|
|
|
|
|
{
|
2021-03-20 21:56:15 +08:00
|
|
|
|
private static DataContext Webcontext;
|
2021-04-16 19:21:56 +08:00
|
|
|
|
private static object myLock = new object();
|
2021-03-28 20:56:27 +08:00
|
|
|
|
|
2021-03-20 21:56:15 +08:00
|
|
|
|
public static void Initialize(DataContext webContext)
|
2021-03-20 14:12:24 +08:00
|
|
|
|
{
|
2021-04-16 19:21:56 +08:00
|
|
|
|
|
|
|
|
|
|
Monitor.Enter(myLock);
|
|
|
|
|
|
{
|
|
|
|
|
|
Webcontext = webContext;
|
|
|
|
|
|
}
|
2021-03-20 14:12:24 +08:00
|
|
|
|
}
|
|
|
|
|
|
public static DataContext GetCurrentDbContent()
|
|
|
|
|
|
{
|
2021-04-16 19:21:56 +08:00
|
|
|
|
|
|
|
|
|
|
DataContext db = CallContext.GetData("DbContext") as DataContext;
|
2021-04-13 12:42:37 +08:00
|
|
|
|
|
2021-03-20 21:56:15 +08:00
|
|
|
|
if (db == null)//线程在数据槽里面没有此上下文
|
|
|
|
|
|
{
|
2021-04-16 19:21:56 +08:00
|
|
|
|
db = Webcontext;
|
|
|
|
|
|
CallContext.SetData("DbContext", db);//放到数据槽中去,DbContext是key,db是value
|
|
|
|
|
|
}
|
2021-04-13 12:42:37 +08:00
|
|
|
|
|
2021-04-16 19:21:56 +08:00
|
|
|
|
try
|
|
|
|
|
|
{
|
|
|
|
|
|
Monitor.Exit(myLock);
|
|
|
|
|
|
}
|
|
|
|
|
|
catch
|
|
|
|
|
|
{
|
2021-04-13 12:42:37 +08:00
|
|
|
|
}
|
2021-04-16 19:21:56 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return db;
|
|
|
|
|
|
|
|
|
|
|
|
|
2021-03-20 14:12:24 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2021-03-20 21:56:15 +08:00
|
|
|
|
private static class CallContext
|
|
|
|
|
|
{
|
|
|
|
|
|
static ConcurrentDictionary<string, AsyncLocal<object>> state = new ConcurrentDictionary<string, AsyncLocal<object>>();
|
2021-03-20 14:12:24 +08:00
|
|
|
|
|
2021-03-20 21:56:15 +08:00
|
|
|
|
public static void SetData(string name, object data) =>
|
|
|
|
|
|
state.GetOrAdd(name, _ => new AsyncLocal<object>()).Value = data;
|
2021-03-20 14:12:24 +08:00
|
|
|
|
|
2021-03-20 21:56:15 +08:00
|
|
|
|
public static object GetData(string name) =>
|
|
|
|
|
|
state.TryGetValue(name, out AsyncLocal<object> data) ? data.Value : null;
|
|
|
|
|
|
}
|
2021-03-20 14:12:24 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|