다음을 통해 공유


3단계: 구성 요소 다시 사용

목표

이 단계에서는 다음에 대해 알아봅니다.

  • 재사용 가능한 구성 요소입니다.
  • 재사용 가능성을 계획하는 방법

설명

이 COM+ 서비스 입문서의 이전 두 부분인 1단계: 트랜잭션 구성 요소 만들기2단계: 여러 구성 요소 간에 트랜잭션 확장은 두 번째 구성 요소를 호출하는 구성 요소를 작성하여 일부 작업을 완료하고 Microsoft SQL Server Pubs 데이터베이스에서 작성자 정보를 업데이트하는 방법을 보여 줍니다. 모든 작업은 단일 트랜잭션으로 보호됩니다. 샘플 구성 요소는 작성자의 데이터를 업데이트하고 작성자의 주소를 확인하는 작업과 COM+에서 제공한 트랜잭션 처리, JIT 활성화동시성 보호 작업에 중점을 두었다.

이 단계에서는 1단계와 2단계에서 만든 구성 요소를 다시 사용하는 방법을 보여 줍니다. 이러한 구성 요소의 디자인에 어떤 의미가 있는지 살펴봅니다. 다음 그림과 같이 를 호출UpdateAuthorAddress하여 데이터베이스에 새 작성자를 추가하는 새 구성 요소 AddNewAuthor를 만드는 것을 의미합니다.

구성 요소를 다시 사용할 때의 흐름을 보여 주는 다이어그램

기존 구성 요소 기능을 다시 사용하는 것 외에도 라는 AddNewAuthor 또 다른 새 구성 요소를 ValidateAuthorName호출합니다. 앞의 그림과 같이 는 ValidateAuthorName 트랜잭션이 아닌 입니다. 이 구성 요소의 트랜잭션 특성 값은 트랜잭션에서 해당 작업을 제외하기 위해 기본 설정(지원되지 않음)에 남아 있습니다. 3단계 샘플 코드에 표시된 것처럼 는 ValidateAuthorName 데이터베이스에서 읽기 전용 쿼리를 수행하며, 이 사소한 작업의 실패로 트랜잭션을 중단할 가능성이 없어야 합니다. 그러나 구성 요소의 AddNewAuthor 트랜잭션 특성 값은 필수로 설정됩니다.

AddNewAuthor, UpdateAuthorAddressValidateAuthorAddress 구성 요소는 모두 트랜잭션에 투표합니다. 이 트랜잭션에서 는 AddNewAuthor 루트 개체입니다. COM+는 항상 트랜잭션에서 만든 첫 번째 개체를 루트 개체로 만듭니다.

이 예제에서는 구성 요소를 쉽게 재사용할 UpdateAuthorAddress 수 있습니다. COM+는 예상 서비스를 자동으로 제공합니다. 그러나 구성 요소의 UpdateAuthorAddress 트랜잭션 특성 값이 처음에 필수가 아닌 새로 필요로 설정된 경우 결과가 달라집니다. 표면에서 두 설정은 비슷하게 표시됩니다. 둘 다 트랜잭션을 보장합니다. 그러나 새로 만들기가 필요한 경우 항상 새 트랜잭션을 시작하고 필수는 개체의 호출자가 트랜잭션이 아닌 경우에만 새 트랜잭션을 시작합니다. 이를 통해 신중하고 신중하게 구성하는 UpdateAuthorAddress 것이 얼마나 중요한지 알 수 있습니다. 그렇지 않으면 COM+가 서비스 요청을 다르게 해석하여 다음 그림과 같이 관련이 없는 두 개의 트랜잭션을 생성했을 수 있습니다.

참고

구성 요소를 다시 사용하는 경우 서비스가 원하는 결과를 지원하도록 구성되어 있는지 확인합니다.

 

예제 코드

AddNewAuthor 구성 요소는 클라이언트가 개체에 대한 참조를 해제할 때까지 개체가 활성 상태로 유지되도록 하여 새 작성자의 일괄 처리를 추가합니다.

Option Explicit
'
'   Purpose:   This class is used for adding a new author.
'
'   Notes:    IMPT:  This component implicitly assumes that it will
'             always run in a transaction. Undefined results may 
'             otherwise occur.
'
'  AddNewAuthor
'
Public Sub AddNewAuthor( _
                        ByVal strAuthorFirstName As String, _
                        ByVal strAuthorLastName As String, _
                        ByVal strPhone As String, _
                        ByVal strAddress As String, _
                        ByVal strCity As String, _
                        ByVal strState As String, _
                        ByVal strZip As String, _
                        ByVal boolContracted As Boolean)
  ' Handle any errors.
  On Error GoTo UnexpectedError

  ' Verify component is in a transaction.
  ' The VerifyInTxn subroutine is described in Step 1.
  VerifyInTxn

  ' Get our object context.
  Dim objcontext As COMSVCSLib.ObjectContext
  Set objcontext = GetObjectContext

  ' Get the IContextState object.
  Dim contextstate As COMSVCSLib.IContextState
  Set contextstate = objcontext

  ' Validate that the author is OK.
  ' The ValidateAuthorName function is described after this function.
  Dim oValidateAuthName As Object
  Dim bValidAuthor As Boolean
  Set oValidateAuthName = CreateObject("ComplusPrimer.ValidateAuthorName")
  bValidAuthor = oValidateAuthName.ValidateAuthorName( _
    strAuthorFirstName, strAuthorLastName)
  If Not bValidAuthor Then
    Err.Raise 999999, "The AddNewAuthor component", _
      "You tried to add an author on the banned list!"
  End If
  
  ' Open the connection to the database.
  Dim conn As ADODB.Connection
  Set conn = CreateObject("ADODB.Connection")

  ' Specify the OLE DB provider.
  conn.Provider = "SQLOLEDB"

  ' Connect using Windows Authentication.
  Dim strProv As String
  strProv = "Server=MyDBServer;Database=pubs;Trusted_Connection=yes"

  ' Open the database.
  conn.Open strProv

  ' Tell the database to actually add the author; use empty strings 
  ' for this part and rely on the UpdateAuthorAddress 
  ' component to validate the address/phone/etc data.
  ' Default Contract flag is off.
  Dim strUpdateString As String
  strUpdateString = "insert into authors values(_
                     '789-65-1234'," & _
                     strAuthorLastName & ", " & _
                     strAuthorFirstName & ", " & _
                     "'(555) 555-5555', ', ', ', '98765', "

  If boolContracted Then
    strUpdateString = strUpdateString + "1)"
  Else
    strUpdateString = strUpdateString + "0)"
  End If

  conn.Execute strUpdateString
  
  ' Close the connection; this potentially allows 
  ' another component in the same transaction to
  ' reuse the connection from the connection pool.
  conn.Close
  Set conn = Nothing
  
  ' Create the UpdateAuthorAddress component.
  Dim oUpdateAuthAddr As Object
  Set oUpdateAuthAddr = CreateObject("ComplusPrimer.UpdateAuthorAddress")
  
  ' The component throws an error if anything goes wrong.
  oUpdateAuthAddr.UpdateAuthorAddress "", strPhone, _
    strAddress, strCity, strState, strZip
    
  Set oUpdateAuthAddr = Nothing
  
  ' Everything works--commit the transaction.
  contextstate.SetMyTransactionVote TxCommit
  
  '  Design issue:  Allow batch additions of new
  '  authors in one transaction, or should each new author be added
  '  in a single new transaction?
  contextstate.SetDeactivateOnReturn False
  Exit Sub
  
UnexpectedError:
  ' There's an error.
  contextstate.SetMyTransactionVote TxAbort
  contextstate.SetDeactivateOnReturn True
  
End Sub

ValidateAuthorName 구성 요소는 데이터베이스에 이름을 추가하기 전에 AddNewAuthor 작성자 이름의 유효성을 검사합니다. 이 구성 요소는 예기치 않은 일이 발생하면 호출자에게 오류를 다시 throw합니다.

Option Explicit
'
'   Purpose:   This class is used for validating authors before
'              adding them to the database.
'
'   Notes:   This component doesn't need to be in a transaction because
'            it is performing read-only queries on the database,
'            especially since these queries are not overlapping with
'            any updates of end-user data. If an unexpected error
'            happens, let the error go back to the caller who
'            needs to handle it.
'

Public Function ValidateAuthorName( _
                        ByVal strAuthorFirstName As String, _
                        ByVal strAuthorLastName As String _
                        ) As Boolean
  ValidateAuthorName = False

  ' Open the connection to the database.
  Dim conn As ADODB.Connection
  Set conn = CreateObject("ADODB.Connection")

  ' Specify the OLE DB provider.
  conn.Provider = "SQLOLEDB"

  ' Connect using Windows Authentication.
  Dim strProv As String
  strProv = "Server=MyDBServer;Database=pubs;Trusted_Connection=yes"

  ' Open the database.
  conn.Open strProv

  ' Suppose another hypothetical table has been added to the Pubs 
  ' database, one that contains a list of banned authors.
  Dim rs As ADODB.Recordset
  Set rs = conn.Execute("select * from banned_authors")
  
  ' Loop through the banned-author list looking for the specified
  ' author.
  While Not rs.EOF
    If rs.Fields("FirstName") = strAuthorFirstName And _
      rs.Fields("LastName") = strAuthorLastName Then
        ' This is a banned author.
        conn.Close
        Set conn = Nothing
        Set rs = Nothing
        Exit Function
    End If
    rs.MoveNext
  Wend
  
  ' None of the added authors found in the banned list.
  ValidateAuthorName = True
  conn.Close
  Set conn = Nothing
  Set rs = Nothing
End Function

요약

  • 구성 요소가 트랜잭션에 투표하지 않도록 하려는 경우가 있습니다.
  • COM+는 비 트랜잭션 구성 요소에 JIT 활성화 또는 동시성 보호를 적용하지 않습니다. 이러한 서비스를 별도로 구성할 수 있습니다.
  • 호출 구성 요소의 구성은 COM+가 호출된 구성 요소의 서비스 요청을 해석하는 방법에 영향을 줍니다.

1단계: 트랜잭션 구성 요소 만들기

2단계: 여러 구성 요소에서 트랜잭션 확장

트랜잭션 구성

확장성을 위한 디자인