我正在编写一个集成测试,我将把一些对象插入数据库,然后检查以确定我的方法是否检索这些对象.
我与数据库的连接是通过NHibernate ...而我创建这样一个测试的常用方法是执行以下操作:
NHibernateSession.BeginTransaction();
//use nhibernate to insert objects into database
//retrieve objects via my method
//verify actual objects returned are the same as those inserted
NHibernateSession.RollbackTransaction();
Run Code Online (Sandbox Code Playgroud)
但是,我最近发现了TransactionScope,它显然可以用于这个目的......
public static int AddDepartmentWithEmployees(Department dept)
{
int res = 0;
DepartmentAdapter deptAdapter = new DepartmentAdapter();
EmployeeAdapter empAdapter = new EmployeeAdapter();
using (TransactionScope txScope = new TransactionScope())
{
res += deptAdapter.Insert(dept.DepartmentName);
//Custom method made to return Department ID
//after inserting the department "Identity Column"
dept.DepartmentID = deptAdapter.GetInsertReturnValue(); …
Run Code Online (Sandbox Code Playgroud) 当Method1()
实例化a TransactionScope
和调用Method2()
也实例化a时TransactionScope
,.NET如何知道它们在同一范围内?我相信它不会在内部使用静态方法,否则它在ASP.NET等多线程应用程序上无法正常工作.
是否可以创建我自己的类似TransactionScope的类,或者原始类是否可以使用只有Microsoft知道它们如何工作的特殊功能?