Windows Communication Foundation (WCF) 提供与企业服务集成的自动机制(请参阅 “与 COM+ 应用程序集成”)。 但是,你可能希望灵活地开发内部使用企业服务中托管的事务组件的服务。 由于 WCF 事务功能基于 System.Transactions 基础结构构建,因此将企业服务与 WCF 集成的过程与指定企业服务之间的 System.Transactions 互作性的过程相同,如 与企业服务和 COM+ 事务的互作性中所述。
若要提供传入流事务与 COM+ 上下文事务之间的所需互作性级别,服务实现必须创建实例 TransactionScope 并使用枚举中的 EnterpriseServicesInteropOption 相应值。
将企业服务与业务运营进行集成
下面的代码演示对 Allowed 事务流执行的操作,该操作创建一个具有 TransactionScope 选项的 Full。 此方案中适用以下条件:
如果客户端启动事务,操作(包括对企业服务组件的调用)将在该事务范围内执行。 使用Full可确保事务与System.EnterpriseServices上下文同步,这意味着环境事务与System.TransactionsSystem.EnterpriseServices上下文相同。
如果客户端不传递事务,则设置TransactionScopeRequired到
true
会为操作创建新的事务范围。 同样,使用 Full 可确保作的事务与组件上下文中使用的 System.EnterpriseServices 事务相同。
任何额外的方法调用也会在同一操作的事务范围内发生。
[ServiceContract()]
public interface ICustomerServiceContract
{
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
void UpdateCustomerNameOperation(int customerID, string newCustomerName);
}
[ServiceBehavior(TransactionIsolationLevel = System.Transactions.IsolationLevel.Serializable)]
public class CustomerService : ICustomerServiceContract
{
[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
public void UpdateCustomerNameOperation(int customerID, string newCustomerName)
{
// Create a transaction scope with full ES interop
using (TransactionScope ts = new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions(),
EnterpriseServicesInteropOption.Full))
{
// Create an Enterprise Services component
// Call UpdateCustomer method on an Enterprise Services
// component
// Call UpdateOtherCustomerData method on an Enterprise
// Services component
ts.Complete();
}
// Do UpdateAdditionalData on an non-Enterprise Services
// component
}
}
如果不需要在操作的当前事务和对事务企业服务组件的调用之间进行同步,则在实例化None实例时使用TransactionScope选项。
将企业服务与客户端集成
下面的代码演示使用 TransactionScope 实例的客户端代码,该实例具有 Full 设置。 在此方案中,对支持事务流的服务操作的调用与对Enterprise Services组件的调用发生在相同的事务范围内。
static void Main()
{
// Create a client
CalculatorClient client = new CalculatorClient();
// Create a transaction scope with full ES interop
using (TransactionScope ts = new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions(),
EnterpriseServicesInteropOption.Full))
{
// Call Add calculator service operation
// Create an Enterprise Services component
// Call UpdateCustomer method on an Enterprise Services
// component
ts.Complete();
}
// Closing the client gracefully closes the connection and
// cleans up resources
client.Close();
}