Archive for August, 2008

AppDomains and AddIn

AppDomains and Addins

What is an Application Domain (AD)?

An Application Domain is a CLR feature that provides a unit of isolation for an application. An AD may be thought of as a lighter weight process boundary. Multiple AppDomains may be created within a host process. The CLR also verifies that the user code in an App domain is type safe. An assembly must be loaded into an application domain before it can run (see default domain). By default, the CLR loads an assembly into the Application Domain containing the code that references it.

Default Domain

When a process that hosts the CLR is created, the CLR automatically creates a default App Domain. Note that there is one CLR per process. I will come back to this in future posts when speaking to versioning, Side by Side (SxS), LockCRL version, etc.. The default App Domain remains as long as the host process lives. The Host code will undoubtly need to live as long as the process, but Add-in’s (Assemblies loaded by the Host) should be isolated from the host code (see isolation).


An isolation boundary provides a level of protection between the Host assembly and the assemblies running in the AD(s). And of course, an Assembly in one AD is also isolated from an assembly loaded in another AD. An isolated assembly may not directly access code or resources in another assembly.

The life time of an Add-in(s) may not be as long as the life time of the host process. The Host should have control over the Add-in’s life time and via isolation the Host has the opportunity to control the temporal nature of Add-in’s. The host may also load multiple Add-in’s into the same App Domain (clumping) where they have like semantics, such as; shared security context, life times, shared resources, etc.. In the case of ASP.net this is the model. Imagine a server application that loaded transient code into its process but never had the ability to unload and therefore release resources. The resources consumed would never be reclaimed.


There is no ability within the CLR to unload an assembly (Why not?) at run time. The ability to unload an assembly is made possible via unloading an AppDomain and thus the assembly or assemblies within the AppDomain.


As a host, you must be conscience of the remoting boundary in your programming model. Since you are crossing an AppDomain boundary (just as you would when crossing a process boundary) your objects need to be MarshalByRef (MBRO) and instantiated via System.Runtime.Remoting. There is a brief discussion on this subject in JasonZ’s blog comments. Alternatively you could use serialization but you loose the reference semantics as you are making a copy. For a great write up on value and reference types follow this link.

There are versioning considerations you need to understand when communicating between components. The good news, is that we have the WinFX AddIn model libraries and forth coming guidance on design considerations to help you in this regard. I will be blogging more on this subject and maybe even co-authoring a book on the subject, if the demand is warranted (hint, hint – tell me if you would find this valuable).


Declaring assemblies to have domain-neutral behavior may be accomplished via the runtime hosting interfaces (see the framework SDK CorBindToRuntimeEx). Loading code that is domain neutral will improve performance on subsequent referencing of the same code in additional AppDomains, because the assembly code pages will be shared across the AppDomains.

So then the question arises as to why not load everything domain-neutral. The primary reason is that domain-neutral code may not be unloaded. So does this conflict with the Add-in model guidance of unloadability and isolation? No, the majority of the scenarios addressed by the Add-in model would not have Add-in’s loaded in the GAC, nor desired to be shared across AD’s. Common functionality offered by the hosting application to the Add-in’s, is a likely candidate for domain-neutrality as opposed to Add-in assembly neutrality. You may wish to reread that last sentence ;-). These classifications of Host provided assemblies are available to consumers (Add-in’s) for the duration of the Host process. So there should be no conflict in the Add-in model isolation and unloadability recommendation and domain-neutrality.

In v1.0 and v1.1 native images that Ngen.exe produces cannot be shared (domain-neutrality) across AD’s. In v2.0, native images that Ngen.exe produces can be shared (domain-neutrality) across AD’s.

AppDomainSetup Properties

There are additional properties to the ones I touch on below, but I wanted to call out two primary properties of interest.


The ApplicationBase is the root directory of the application. When an AppDomain is created, it inherits the ApplicationBase of the AppDomain creator (the Host in the Add-in model). When an assembly is loaded from disk, the CLR uses this root as the probing path. It is very likely that the Add-in will be installed in a different directory than the host application. In the majority of the cases, the two are installed and uninstalled independently of each other.


The optional configuration file, is an XML file, that has settings for the application. Most people are familiar with the concept when they think about machine.config. The configuration file can be used for declaring a startup shim, versioning rules, etc.. The configuration file will be something along the lines of MyApp.exe.config or MyApp.dll.config.


A host can control policy in two ways.
1. The host can provide evidence when creating the AD.
2. The host can restrict the permissions granted at a policy level.


It could be argued that this is a lot of work. However, the CLR and the framework, already simplify much of this for you. Of course, as the Host, you must hook up all the various functionality provided via the framework. The number of Hosts (ISV’s and large application providers) that need to provide this functionality is small in comparison to the number of customizations/applications/Add-in’s that will be written against a Host application. So the complexity, and thus the burden, is placed on a significantly fewer number of developers. And to further simplify the lives of ISV’s, which is my current job :-), we have the System.AddIn* offering.



Read Full Post »

PRISM (Composite WPF) is a project endorsed by Microsoft specifically targeted at WPF, and hosted on CodePlex. According to Glenn Block, a Technical Product Planner for Microsoft, PRISM offers the following benefits:
o Provides complete support for WPF
o Dynamically composes user interface components
o Application modules are developed, tested and deployed by separate teams
o Allows incremental adoption
o Provides an integrated user experience
Right now, PRISM “includes a reference implementation, a reusable library code and pattern guidance”, but the plan is to develop a framework which composite applications can be built upon.

The Microsoft Patterns & Practices Team created the Prism CodePlex Project. Prism is a set of assets for developing Composite WPF applications. Prism includes a reference implementation, reusable library code and pattern guidance. Using Prism enables designing a composite application that is composed of many discrete, loosely coupled modules.

Prism means
– Composite WPF
– Composite Application Guidance for WPF

Prism is a set of guidance coming out of Patterns and Practices for building composite applications in WPF.

Composite Application – It’s essentially an application that is dynamically composed from a set of different pieces

How different Prism is from CAB?

In one sense very different because Its not taking one line of code from CAB into Prism, so it’s a completely new effort. The reasoning for that is several fold: one reason is that WPF is entirely different than WinForms, completely different paradigm, the technology is different. There is a lot of things in CAB that have to reinvent the wheel because there was no similar construct in WinForms, but now actually things like commanding, for example, is build in to WPF. So for that reason plus combined with a large amount of feedback that microsoft p&p team got from customers who use Smart Client Software Factory which built on top of CAB and CAB, about how difficult it was to grok the number of abstractions, the fact that it was very imposing. I really had to accept every aspect of it which brought along a bunch of heaviness with it, and also it required me to build from scratch. So we’ve got costumers that are extremely happy with CAB and SCSF, but even the people that have been very happy have had a bunch of pains getting there, so we felt for that reason that we had a chance to both address delivering the right kind of guidance for the technology, being WPF, and at the same time to address the concerns that we heard from many customers

Components Mappings – CAB and PRISM

CAB Commands – Replaced with WPF Commands. See the Commanding Quick Start.
CAB EventTopics – See the IEventAggregator Service interface in the Events Quick Start.
CAB Items – Again replace with DI Container of your choice.
CAB Services – Service dependencies are resolved the DI Container similar to CAB.
CAB Smart Parts – Lots of options here – Any WPF User control can be a smart part or you can simply display a model with an associated DataTemplate (an approach I favor). Separated presentation parts are again wired through the DI container.
CAB State – Personally I never used this much in CAB, but you can resolve global state through the DI container if you wish.
CAB UIExtensionSites – with WPF’s flexibility a module can just add new items to a menu/toolbar without extra functionality. It could be a Comp WPF region.
CAB WorkItems – You can create you own hierarcy of containers, but Comp WPF seems to favor simply one container. What’s more important is to segment you business logic. See WorkItem controller below.
CAB Workspaces – Comp WPF uses regions and Region Manager Service. You can name regions in your XAML with an attached property.

PRISM Technical & Design Concepts.

Technical Concepts

1. Bootstrapper
– The bootstrapper is responsible for the initialization of an application built using the Composite Application Library. Having a bootstrapper gives you more control of how the Composite Application Library components are wired up to your application. For example, if you have an existing application that you are adding the Composite Application Library to, you can initialize the bootstrapping process after the application is already running.
In a traditional Windows Presentation Foundation (WPF) application, a startup Uniform Resource Identifier (URI) is specified in the App.xaml that launches the main window. In an application created with the Composite Application Library, it is the bootstrapper’s responsibility. This is because the shell relies on services, such as the Region Manager, that need to be registered before the shell can be displayed. Additionally, the shell may rely on other services that are injected into its constructor. For more information about the shell, see the Shell and View technical concept.

The Composite Application Library includes a default abstract UnityBootstrapper class that handles this initialization using the Unity container. Many of the methods on the UnityBootstrapper class are virtual methods. You should override these methods as appropriate in your own custom bootstrapper implementation. If you are using a container other than Unity, you should write your own container-specific bootstrapper.

2. Container and Services – The Composite Application Library is designed to support other dependency injection containers. Core services, such as the ModuleLoader service, are container agnostic. They use the Composite Application Library container or IContainerFacade interface for resolving, instead of directly accessing the containers. The Composite Application Library provides the UnityContainerAdapter, which is a Unity-specific implementation of this interface. This container is registered by the UnityBootstrapper.

3. Module – A module in the Composite Application Library is a logical unit in your application. Modules assist in implementing a Modularity design. These modules are defined in such a way that they can be discovered and loaded by the application at run time. Because modules are self-contained, they promote separation of concerns in your application. Modules can communicate with other modules and access services through various means. They reduce the friction of maintaining, adding, and removing system functionality. Modules also aid in testing and deployment.
4. Region – Conceptually, a region is a mechanism that developers can use to expose Windows Presentation Foundation (WPF) controls to the application as components that encapsulate a particular visual way of displaying and laying out views. Regions can be accessed by name and support adding or removing views. This decoupling allows the appearance and behavior (look and feel) of the application to evolve independently of the views that appear within the region (for more information about views, see the Shell and View technical concept).
Regions are intended to enable a compositional pattern and are commonly used in template layouts and multiple view layouts.
5. Shell and View – The shell is the main window of the application where the primary user interface (UI) content is contained. The shell may be composed of multiple windows if desired, but most commonly it is just a single main window that contains multiple views. The shell may contain named regions where modules can add views. It may also define certain top-level UI elements, such as the main menu and toolbar. The shell also defines the overall appearance and behavior (look and feel) for the application. It may define styles and borders that are present and visible in the shell layout itself, and it may also define styles, templates, and themes that get applied to the views that are plugged into the shell.
Views are the composite portions of the user interface that are contained in the shell’s window(s). It is easiest to think about a view as a user control that defines a rectangular portion of the client area in the main window. However, views in the Composite Application Library do not have to be defined with a user control. You can use a Windows Presentation Foundation (WPF) data template to define a view that will be rendered based on the data in your model. A view could also share screen real estate with other views due to the rendering and compositing capabilities of WPF. In simple terms, a view is just a collection of user interface elements that define part of the rendering of the user interface. It is a unit of encapsulation for defining the separable portions of your UI.
6. EventAggregator -The EventAggregator service is primarily a container for events that allow decoupling of publishers and subscribers so they can evolve independently. This decoupling is useful in modularized applications because new modules can be added that respond to events defined by the shell or, more likely, other modules.
In the Composite Application Library, EventAggregator allows subscribers or publishers to locate a specific EventBase. The event aggregator also allows for multiple publishers and multiple subscribers
7. Commands – Commands are a way to handle user interface (UI) actions. They are a loosely coupled way to bind the UI to the logic that performs the action.
When building composite applications, presentation design patterns such as Model-View-Presenter (MVP) and Model-View-Controller (MVC) are often used to separate the UI logic from the UI layout and presentation. When implementing these patterns with Windows Presentation Foundation (WPF), the presenter or controller handles commands but lives outside the logical tree. WPF-routed commands deliver command messages through UI elements in the tree, but the elements outside the tree will not receive these messages because they only bubble up or down from the focused element or an explicitly stated target element. Additionally, the WPF-routed commands require a command handler in the code behind.
The Composite Application Library introduces two new commands that can be routed outside the boundaries of the logical tree and that do not require handling logic in the code behind. The commands are custom implementations of the ICommand interface defined by WPF, and they implement their own routing mechanism to get the command messages delivered to objects outside of the logical tree. The commands in the Composite Application Library include DelegateCommand and CompositeCommand.
8. Communication – When building large complex applications, a common approach is to divide the functionality into discrete module assemblies. It is also desirable to minimize the use of static references between these modules. This allows the modules to be developed, tested, deployed, and updated independently and forces loosely coupled communication.
When communicating between modules, you can use commanding, event aggregation, or shared services. Use the following to help decide which approach to use:
• Commanding. Use this in response to user gestures and custom enablement.
• Event aggregator. Use this to publish an event across modules.
• Shared services. Use this if neither of the preceding is applicable

Design Concepts

1. UI Composition – Composite applications typically compose their user interfaces (UIs) from various loosely coupled visual components, otherwise known as views, to deliver an integrated application experience. To the user, the application appears as a seamless program that offers many capabilities
2. Modularity – Modularity is designing a system that is divided into a set of functional units (named modules) that can be composed into a larger application. A module represents a set of related concerns. It can include components, such as views or business logic, and pieces of infrastructure, such as services for logging or authenticating users. Modules are independent of one another but can communicate with each other in a loosely coupled fashion.
A composite application exhibits modularity. Imagine an online banking program. The user can access a variety of functions, such as transferring money between accounts, paying bills, and updating personal information from a single user interface (UI). However, behind the scenes, each of these functions is a discrete module. These modules communicate with each other and with back-end systems such as database servers. Application services integrate components within the different modules and handle the communication with the user. The user sees an integrated view that looks like a single application
3. Container – Applications based on the Composite Application Library are composites that potentially consist of many loosely coupled modules. They need to interact with the shell to contribute content and receive notifications based on user actions. Because they are loosely coupled, they need a way to interact and communicate with one another to deliver the required business functionality.
To tie together these various modules, applications based on the Composite Application Library rely on a dependency injection container. The container offers a collection of services. A service provides functionality to other modules in a loosely coupled way through an interface and is often a singleton. The container creates instances of components that have service dependencies. During the component’s creation, the container injects any dependencies that the component has requested into it. If those dependencies have not yet been created, the container creates and injects them first.
In some cases, the container itself is resolved as a dependency. For example, modules will often register views of the container by having the container injected.
There are several advantages of using a container:
• A container removes the need for a component to have to locate its dependencies or manage their lifetime.
• A container allows swapping the implementation of the dependencies without affecting the component.
• A container facilitates testability by allowing dependencies to be mocked.
• A container increases maintainability by allowing new services to be easily added to the system.
In the context of an application based on the Composite Application Library, there are specific advantages to a container:
• A container injects module dependencies into the module when it is loaded.
• A container is used for registering and resolving presenters and views.
• A container creates presenters and presentation models and injects the view.
• A container injects the composition services, such as the region manager and the event aggregator.
• A container is used for registering module-specific services, which are services that have module-specific functionality.


Read Full Post »

Managed AddIn Framework

MAF (Managed AddIn Framework)

The Managed Add-in Framework defines a programming model, built on top of .NET that allows applications to dynamically load and communicate with generic components at runtime. We provide a solution for creating independently versioning, mutually distrustful components, and allow them to work together. We tackle the two problematic – versioning and isolation – together.

At PDC05, Thomas Quinn, an architect on our team, responsible for VSTO and VSTA, and Jim Miller, a CLR architect, responsible for several platform components related to versioning support in the CLR, among other things, jointly presented the platform framework for managed Addin’s. See the PDC FUN309 session.

What is an Add-In?

An add-in is traditionally thought of as custom code (a customization), written by a third party that is loaded and activated by a Host application (Word, Excel, etc…) upon the host starting up. The host makes their programmable API (Object Model) available to the customization assembly. In the case of the Office host applications, the Application object, which is the root of the hierarchical object model, is made available to the Add-in. I will use “Addin” in a more generic sense to mean code that is discovered based upon some event (The host Starting up, the loading of a document, etc..). Later, I will argue that this definition is too narrow.


Note that the definition I just articulated was a dynamic loading mechanism as opposed to static. An Addin is also generally loaded into the host’s process. This requirement then adds the concern of isolation. The host needs to be isolated from errant behavior of the Addin and Addin’s should in many cases, be isolated from each other. Although it is implied, the two components also need to agree on some communication protocol (a contract).

An Addin should be able to be loaded/unloaded of its own accord or loaded/unloaded by the host.
The requirement to Load/Unload Addin’s dynamically, adds the further requirement that the Host and Addin need to version independently.

A picture is worth a thousand words

Text image representation

Host Application – Adapter IContract | IContract – Proxy – Add-In

Host Process – Implements Contract IMyContra | ct : IContract – Addin Friendly facade/OM – Customization

<————————————-Direction of Call————————————————————–

Vertical bar (|) represents a boundary (Process, AppDomain)


Pre-defined interfaces used as explicit, agreed upon protocols for communication between two endpoints.

• All user defined contracts derive from IContract the base interface.
• A Contract is roughly analogous to a COM Interface.
• Possibly a better description from Thomas Quinn (aka TQ), “A Contract is any .NET interface, derived from IContract (to be defined), and having the following properties: it never versions beyond servicing, the containing assembly contains only other Contracts or non-versioning types, and it exposes in its method signatures only other Contracts, or fully known, loadable, and serializable type. It explicitly cannot contain the types System.Object, System.Type, System.MarshalByRefObject, any type from System.Reflection nor delegates or events, nor any other type which may cause the exposure of an implementation type”


• Implement contracts.
• Adapters serve the purpose of adapting between a friendly .NET Framework based programming model on each end and the less friendly, and more restricted contracts in the middle. Adapters are the object model.
• Similar in concept to web services. Although MAF is designed for Object Oriented services versus a Services Oriented model. We have worked with the Indigo team (aka. Windows Communications Foundation) on ensuring the two models are in alignment and they will continue to evolve in conjunction with each other. In a nutshell, both models prescribe an explicit understanding of boundaries (web service boundaries are machine), proxy generation, agreed upon contracts, separation of the definition and implementation and consumption, etc…


• Consume (call into) contracts.
• Exposes an object oriented, .NET Friendly surface to its consumers (Add-in’s).
• Similar in concept to consuming web services.
• Makes requests across the App Domain boundary.

.Net platform libraries

System.AddIn.dll and the System.AddIn namespace

• The NS will first be made available to the public in the VSTA/O12 release in the second half of 2006.
• The VSTA product and MAF have been announced at PDC 2005.
• First available in VSTA/O12 and then made available broadly in Orcas as part of the platform (CLR).
• This System.AddIn.dll is the Add-in loader
• An Add-in is any component that is discovered and loaded at runtime by a hosting application and that version separately from the hosting application. The loader is the component that is responsible for the App domain creation utilizing a customizable security manager, loads and activates Addin’s in specified App domains and provides Add-in unloading of specified App domains. The level of unloading in the CLR is by process or AppDomain.


• This dll may not version (first tenant of a contract).
• First available in VSTA/O12 and then made available broadly in Orcas as part of the platform (CLR),
• Defines base contract IContract
• Provides a remote kind of reflection. The contracts mimic the similarly named types in the System.Reflection namespace without providing the full implementation. The goal here is to be able to invoke methods and properties, set and get fields and handle events on objects across the remoting boundary without having direct access to that object’s Type. We provide a remote type surrogate that performs the duties of Type and its friends.


Read Full Post »