The add-in model's remoting capabilities complicate lifetime management. Because garbage collection does not adequately support reclaiming objects in multiple application domains, the add-in model provides its own system of lifetime management. This management system uses a reference-counting system and the common language runtime's remoting services.
The add-in model's lifetime management system can span multiple application domains and isolated processes to make sure that objects, contracts, and add-ins are disposed and their application domains are unloaded. The system does this by maintaining a token handle (ContractHandle) to the add-in during the time that the add-in services a call from the host.
To implement lifetime management, you must acquire a lifetime token whenever a contract is used in a contract-to-view adapter and then revoke the lifetime token when the adapter is finished with it. The ContractHandle class does this work for you if you use it in your adapters. If your pipeline passes custom types, you must acquire the token handle in all contract-to-view adapter classes that you implement. For more information about contract-to-view adapters, see Contracts, Views, and Adapters.
The ContractHandle class takes the contract as its constructor. The following example shows how to set the lifetime token handle in a host-side adapter.
The ContractHandle is critical to lifetime management. If you fail to keep a reference to the ContractHandle object, garbage collection will reclaim it, and the pipeline will shut down when your program does not expect it. This can lead to errors that are difficult to diagnose, such as AppDomainUnloadedException. Shutdown is a normal stage in the life of a pipeline, so there is no way for the lifetime management code to detect that this condition is an error.
Once you acquire the token handle, the system takes care of all lifetime management functions and requires no additional programming.
Under the add-in model, the host and add-ins operate as if their own lifetime management was controlled by the garbage collector. Their local references get disposed and that causes any remote references to be disposed and collected.