服务组件示例(zz)
zz from
http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/cpguide/html/cpconservicedcomponentexample.asp
下面的示例是一个包括客户端和服务器两部分的服务组件。在该示例中,Account 类是从 ServicedComponent 类派生的,这样可确保 Account 对象的上下文在 COM+ 中承载。此示例应用了下面的属性:
- TransactionAttribute 应用于
Account类以将事务设置为 Required;此操作相当于使用 Windows“控制面板”中的“组件服务”管理工具设置 COM+ 组件的事务支持。 - AutoCompleteAttribute 应用于 Post 方法。如果在执行该方法期间生成未处理的异常,此属性指示运行库自动对事务调用 SetAbort 函数;否则,运行库调用 SetComplete 函数。
除此示例中使用的属性外,各种程序集级的属性也用于提供 COM+ 注册信息。对于手动注册,服务组件必须具有强名称,并应放在全局程序集缓存 (GAC) 中。有关程序集的其他信息,请参见具有强名称的程序集。
注意 放置在 GAC 中的程序集不能使用动态注册。如果创建了服务器应用程序,则在该应用程序可以使用之前,必须用 Windows 安装程序将程序集及其依赖的所有程序集添加到全局程序集缓存 (GAC) 中;否则,该应用程序将生成异常。
BankComponent 服务器
[Visual Basic] Imports System.EnterpriseServices Imports System.Runtime.CompilerServices Imports System.Reflection ' Supply the COM+ application name. <assembly: ApplicationName("BankComponent")> ' Supply a strong-named assembly. <assembly: AssemblyKeyFileAttribute("BankComponent.snk")> Namespace BankComponent <Transaction(TransactionOption.Required)> _ Public Class Account Inherits ServicedComponent <AutoComplete()> _ Public Sub Post(accountNum As Integer, amount As Double) ' Updates the database; no need to call SetComplete. ' Calls SetComplete automatically if no exception is generated. End Sub End Class End Namespace [C#] using System.EnterpriseServices; using System.Runtime.CompilerServices; using System.Reflection; // Supply the COM+ application name. [assembly: ApplicationName("BankComponent")] // Supply a strong-named assembly. [assembly: AssemblyKeyFileAttribute("BankComponent.snk")] namespace BankComponent { [Transaction(TransactionOption.Required)] public class Account : ServicedComponent { [AutoComplete] public bool Post(int accountNum, double amount) { /* Updates the database; no need to call SetComplete. Calls SetComplete automatically if no exception is generated. */ return false; } } }
BankComponent 客户端
[Visual Basic] Imports BankComponent Public Class Client Shared Sub Main() Dim Account As New Account() ' Post money into the account. Account.Post(5, 100) End Sub End Class [C#] using BankComponent; namespace BankComponentConsoleClient { class Client { public static int Main() { try { Account act = new Account(); // Post money into the account. act.Post(5, 100); return(0); } catch { return(1); } } } }
Makefile.bat
可以按如下所示编译服务器和客户端:
[Visual Basic] sn –k BankComponent.snk vbc /t:library /r:System.EnterpriseServices.dll Bank.vb vbc /r:Bank.dll /r:System.EnterpriseServices.dll BankClient.vb [C#] sn –k BankComponent.snk csc /t:library /r:System.EnterpriseServices.dll Bank.cs csc /r:Bank.dll BankClient.cs

浙公网安备 33010602011771号