Search code examples
asp.netsession-statecom+

ASP.NET COM+ Dispose Exception


our ASP.NET application is using COM+ to connect to Database

we have this structure:

  1. A Base Class :

    Imports System.EnterpriseServices

    Public Class Base Inherits ServicedComponent

  2. A Child Class:

     Public Class Member Inherits Base
    

    'Propreties . . .

    'Methods
    Public Sub SetMember(ByVal SelectedQueue As String)
            ...
    End Sub
    

In a Aspx page, we search for a member and set details:

Dim newMember As Member =  New Member 
newMember.SetMember(MemberNumber)
Session("SelectedMember") = newMember

We then dispose newMember:

 If Not newMember Is Nothing Then
                newMember.Dispose()
 End If

but whenver we access the session we got an exception:

   If Not Session("SelectedMember") Is Nothing Then
                'Something
            Else
                'Something else
            End If 

the exception is : Cannot access a disposed object. Object name: 'ServicedComponent'.

How can I dispose the object but keep my session valid?


Solution

  • I can see what you're doing wrong, but can't be clear on what would be right. Your logic as stated is:

    1. Obtain object.
    2. Store object.
    3. Clean-up object, rendering it useless.
    4. Retrieve object.
    5. Use object.

    Having 3 before 5 makes no sense.

    If the object is quick to obtain, you should just do so on every page. (Often people over-estimate the cost of this).

    If the object is slow to obtain, and it makes sense to store for a long term, then it shouldn't need to be cleaned-up. What is Dispose() actually doing here? With it obtaining and releasing resources used by members as needed.

    I suspect that the first is the one to go for here, but that's mostly a guess.

    I'd also be concerned when you talk about the database, does your object hold a database connection? If so, and pooling is available, then you should be releasing those connections as fast as possible, rather than holding onto them.