CLR Contexts

[This is a very old article I wrote back in 2002 when I worked for a company which built MRI scanners and was subsequently bought by Oxford Instruments. With COM being once again relevant with the introduction of WinRT, I thought it might be useful to revisit some core COM concepts.]

Details

Definitions

A Context is a way to group together CLR objects having similar runtime (execution) requirements. Contexts are created as needed by the CLR. Cross-context calls require proxies, in a similar manner to cross-Apartment calls in COM.

Execution requirements could include:

  • Synchronisation
  • Transactional support
  • Database updates

Contexts also allow arbitrary message processing to be ‘plugged-in’ to the method-processing architecture by the use of Proxies.

Example

CLR-Contexts-1

CLR Process 1 contains a single AppDomain, which in turn contains two Contexts. Object C must be marked with special processing requirements (say, Interlocked access), and so is placed in a Context which supports this feature. The default (first) Context has no special processing features.

Objects A & B were marked with no special requirements, and so were placed in the Default Context. In order to access Object C, Object B must call through the Proxy. To B, the Proxy appears just like C; in fact B does not know that a proxy is being used. Likewise, if C needs to call A, it uses a Proxy which resembles A in terms of method signatures etc.

Context Creation

The CLR creates Contexts automatically as required: if the Context attributes of the current context do not fit the attributes of the object about to be created, then a new Context is created, and the object placed in there.

Sinks & Properties

Sinks and Properties are entities within Context Proxies which allow interception of cross-Context Object access, and the ‘plugging-in’ of arbitrary additional or replacement processing of method calls. For example, a Sink may decide, based on some security settings, to refuse to pass on a method call to the real object and simply return False:

  • Sink  – read-write access to cross-Context messages
  • Property – read-only access to messages

A typical use of a Sink would be to acquire and release a Synchronisation lock around a method call:

CLR-Contexts-2

This means that the client object (CLR-Contexts-3) does not need to know anything about synchronisation locks, and can be re-used on a scenario without them, or indeed with some other type of processing around the method call.

Comments

This document is based on a lecture given at DevWeek 2002.

Glossary

Context-Agile Object ………………… object refs can be passed between Contexts

Context-Bound Object ………………. object access between Contexts is via a proxy

AppDomain ……………………………… logical process space within the CLR

Join the discussion...

This site uses Akismet to reduce spam. Learn how your comment data is processed.