If you want to implement distributed database transaction operations, you can rely on the MTS/COM + service in. NET Framework to support automatic transaction operations. COM + uses DTC (Microsoft distribution Transaction Coordinator) as the Transaction Manager and Transaction Coordinator to run transactions in a distributed environment. This allows. Net to perform operations across multiple resources. The procedure is as follows:
First, create a new "class library" project. Then, in this project, our class inherits the servicedcomponent class and marks its attribute as "transaction" (transaction ), Code As follows:
[Transaction (transactionoption. Required)]
Public class mydtc: servicedcomponent
Then we can use the contextutil method provided by the Enterprise Library to implement multi-database operation rollback. The Code is as follows:
Try
{
Myconn1.open ();
Console. writeline ("connection1 is successful! ");
Mydomain1.commandtext = "spinsertmyinfo ";
Myapps1.parameters. Add ("@ ID", 6 );
Mydomain1.parameters. Add ("@ name", "Remy ");
Myapps1.executenonquery ();
Myconn2.open ();
Console. writeline ("connection2 is successful! ");
Mydomain2.commandtext = "spinsertvalue ";
Mydomain2.parameters. Add ("@ num", 11 );
Mydomain2.parameters. Add ("@ systemtime", "2005-5-31 ");
Mydomain2.parameters. Add ("@ numtest", 19 );
Mydomain2.executenonquery ();
Contextutil. setcomplete ();
}
Catch (exception)
{
Contextutil. setabort ();
}
Finally
{
Myconn1.dispose ();
Myconn2.dispose ();
}
Finally, we must set some required attributes for Assembly to ensure that it can be correctly registered as a COM + service. The Code is as follows:
Using system;
Using system. Data;
Using system. Data. sqlclient;
Using system. enterpriseservices;
Using system. reflection;
Using system. runtime. compilerservices;
[Assembly: applicationname ("mydtc")]
[Assembly: assemblykeyfileattribute ("C: \ mydtc. SNK ")]
[Assembly: applicationactivation (activationoption. server)]
then we use regsvcs XXX. DLL registers our build as a COM + service. Finally, we only need to write a client to call this COM + service to implement multi-database transaction operations.
here are some of the information I found:
"serviced component overview": http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpguide/html/cpconservicedcomponentoverview. asp
"Writing Serviced components": http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpguide/html/cpconwritingservicedcomponents. asp