public class StudentBL : IStudentService
{
private ILogger mLogger;
private readonly IStudentDA mStudentDa;
private readonly IValueService mValueService;
public StudentService(IStudentDA studentDa,IValueService valueService)
{
mLogger = LogManager.GetCurrentClassLogger();
mStudentDa = studentDa;
mValueService = valueService;
}
[TransactionCallHandler]
public IList<Student> GetStudentList(Hashtable paramsHash)
{
var list = mStudentDa.GetStudents(paramsHash);
var value = mValueService.FindAll();
return list;
}
}
public class StudentDA : IStudentDA
{
private SqlSugarClient db;
public StudentDA()
{
db = SugarManager.GetInstance().SqlSugarClient;
}
public IList<Student> GetStudents(Hashtable paramsHash)
{
return db.Queryable<Student>().AS("T_Student").With(SqlWith.NoLock).ToList();
}
}
public class SugarManager
{
private static ConcurrentDictionary<string,SqlClient> _cache =
new ConcurrentDictionary<string, SqlClient>();
private static ThreadLocal<string> _threadLocal;
private static readonly string _connStr = @"Data Source=localhost;port=3306;Initial Catalog=thy;user id=root;password=xxxxxx;Charset=utf8";
static SugarManager()
{
_threadLocal = new ThreadLocal<string>();
}
private static SqlSugarClient CreatInstance()
{
SqlSugarClient client = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = _connStr, //必填
DbType = DbType.MySql, //必填
IsAutoCloseConnection = true, //默认false
InitKeyType = InitKeyType.SystemTable
});
var key=Guid.NewGuid().ToString().Replace("-", "");
if (!_cache.ContainsKey(key))
{
_cache.TryAdd(key,new SqlClient(client));
_threadLocal.Value = key;
return client;
}
throw new Exception("创建SqlSugarClient失败");
}
public static SqlClient GetInstance()
{
var id= _threadLocal.Value;
if (string.IsNullOrEmpty(id)||!_cache.ContainsKey(id))
return new SqlClient(CreatInstance());
return _cache[id];
}
public static void Release()
{
try
{
var id = GetId();
if (!_cache.ContainsKey(id))
return;
Remove(id);
}
catch (Exception e)
{
throw e;
}
}
private static bool Remove(string id)
{
if (!_cache.ContainsKey(id)) return false;
SqlClient client;
int index = 0;
bool result = false;
while (!(result = _cache.TryRemove(id, out client)))
{
index++;
Thread.Sleep(20);
if (index > 3) break;
}
return result;
}
private static string GetId()
{
var id = _threadLocal.Value;
if (string.IsNullOrEmpty(id))
{
throw new Exception("内部错误: SqlSugarClient已丢失.");
}
return id;
}
public static void BeginTran()
{
var instance=GetInstance();
//开启事务
if (!instance.IsBeginTran)
{
instance.SqlSugarClient.Ado.BeginTran();
instance.IsBeginTran = true;
}
}
public static void CommitTran()
{
var id = GetId();
if (!_cache.ContainsKey(id))
throw new Exception("内部错误: SqlSugarClient已丢失.");
if (_cache[id].TranCount == 0)
{
_cache[id].SqlSugarClient.Ado.CommitTran();
_cache[id].IsBeginTran = false;
}
}
public static void RollbackTran()
{
var id = GetId();
if (!_cache.ContainsKey(id))
throw new Exception("内部错误: SqlSugarClient已丢失.");
_cache[id].SqlSugarClient.Ado.RollbackTran();
_cache[id].IsBeginTran = false;
_cache[id].TranCount = 0;
}
public static void TranCountAddOne()
{
var id = GetId();
if (!_cache.ContainsKey(id))
throw new Exception("内部错误: SqlSugarClient已丢失.");
_cache[id].TranCount++;
}
public static void TranCountMunisOne()
{
var id = GetId();
if (!_cache.ContainsKey(id))
throw new Exception("内部错误: SqlSugarClient已丢失.");
_cache[id].TranCount--;
}
}
public class SqlClient
{
public SqlSugarClient SqlSugarClient;
public bool IsBeginTran = false;
public int TranCount = 0;
public SqlClient(SqlSugarClient sqlSugarClient)
{
this.SqlSugarClient = sqlSugarClient;
}
}
[TransactionCallHandler]
public IList<Student> GetStudentList(Hashtable paramsHash)
{
var list = mStudentDa.GetStudents(paramsHash);
var value = mValueService.FindAll();
return list;
}
public class MyClass : IMyClass
{
public void MyMethod()
{
Console.WriteLine("My Mehod");
}
}
public class TestIntercept : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("before");
invocation.Proceed();
Console.WriteLine("after");
}
}
var proxyGenerate = new ProxyGenerator();
TestIntercept t=new TestIntercept();
var pg = proxyGenerate.CreateClassProxy<MyClass>(t);
pg.MyMethod();
//输出是
//before
//My Mehod
//after
public class TransactionInterceptor : IInterceptor
{
private readonly ILogger logger;
public TransactionInterceptor()
{
logger = LogManager.GetCurrentClassLogger();
}
public void Intercept(IInvocation invocation)
{
MethodInfo methodInfo = invocation.MethodInvocationTarget;
if (methodInfo == null)
{
methodInfo = invocation.Method;
}
TransactionCallHandlerAttribute transaction =
methodInfo.GetCustomAttributes<TransactionCallHandlerAttribute>(true).FirstOrDefault();
if (transaction != null)
{
SugarManager.BeginTran();
try
{
SugarManager.TranCountAddOne();
invocation.Proceed();
SugarManager.TranCountMunisOne();
SugarManager.CommitTran();
}
catch (Exception e)
{
SugarManager.RollbackTran();
logger.Error(e);
throw e;
}
}
else
{
invocation.Proceed();
}
}
}
[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public class TransactionCallHandlerAttribute : Attribute
{
public TransactionCallHandlerAttribute()
{
}
}
proxyGenerate.CreateClassProxy<MyClass>(t);
using System.Reflection;
using Autofac;
using Autofac.Extras.DynamicProxy;
using Module = Autofac.Module;
public class BusinessModule : Module
{
protected override void Load(ContainerBuilder builder)
{
var business = Assembly.Load("FTY.Business");
builder.RegisterAssemblyTypes(business)
.AsImplementedInterfaces().InterceptedBy(typeof(TransactionInterceptor)).EnableInterfaceInterceptors();
builder.RegisterType<TransactionInterceptor>();
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有