Removing SmartParts from a WorkItem

A common and perhaps a little painful problem while working in CUIB (using SCSF) is
disposing the smart parts from a WorkItem. If smart parts are not disposed
properly one may get an exception like "Cannot access the object in its
current state" and in cases where we are using TabWorkspace it is often
difficult to predict the behavior.

The problem here I see is the way WorkItem
is understood. A WorkItem is primarily seen as a container to manage objects.
The normal tendency is to have all the smart parts added to the WorkItem and
later retrieve the SmartPart from the WorkItem to accomplish certain use cases.
This is not a good practice to follow; a WorkItem should be seen
as something that is used to accomplish a use case e.g. In a TabWorkspace
we can have creating a tab as a use case. Each use case needs to be
encapsulated in a WorkItemController class. Adding and also disposing of smart
parts need to be done in this class.

Let me try to elucidate how this needs to
be done-Let us consider a simple use case where on click of a button a tab
needs to be created in the TabWorkspace. The tab needs to
display a SmartPart. Straight forward of doing this would be something
like this-In the Command Handler of the button

The problem with this approach
will be disposing of the SmartPart from the WorkItem when the use case ends -
in our case closing of the tab. Of course we can remove SmartPart from the
WorkItem by calling the Remove method on the WorkItem. This is not the right
way to as SmartPart would not be completely disposed from the WorkItem and we
will run into problems when we try add to the SmartPart again to the WorkItem
and in some cases we may experience weird behavior.

The right way to tackle this
problem is to encapsulate all the logic pertaining to a use case in a
WorkItemController class.

Creating WorkItemController
Class to define a Use Case

Create a class say MyController
which inherits from WorkItemController class. WorkItemController comes with
SCSF and can be found in Infrastructure.Interface Project. All the logic
including adding\removing SmartParts pertaining to the use case ought to be
there in this class.

Comments

Nice post. I knew that those guys(smartparts) were hanging somewhere around but did not know how to dispose them. We are developing stuff using CAB/SCSF and just a few comments how we are doing this. First we are loading smartparts in the Run() method of the WorkItem Controller (What is your opinion about that?)