Silverlight how to: On-demand assembly deployment
One of the cool new features of Silverlight 2 is the concept of on-demand deployment of assemblies. In most interactive development there is a desire to minimize the amount of data a user has to download to get your RIA up and running. The application package (XAP) size can grow quite quickly if one tries to include all of resources required to run the entire application. In Silverlight 2 we have the concept of a XAP file or compressed package (zip file). By default, the XAP contains an application assembly and any Silverlight assemblies that your application is dependent on (System.Xml.Linq, etc). In Silverlight 2 we have the ability to generate more than one XAP file giving us the opportunity to deploy additional assemblies on demand, asynchronously to the initial payload.
To leverage this technology one has to understand the concept of “AssemblyParts” and how reflection is used to extract an assembly from a downloaded XAP. The following example will show how one can code this functionality in Silverlight 2 Beta 1.
The first step in downloading an additional assembly is to go and get the XAP package. Note the use of a BaseAddress. In my example the base address is http://localhost/MultipleXap_Web/.
1 2 3 4 5 | Uri addressUri = new Uri(_baseUri, "ClientBin/MultipleXap1.xap") |
Once downloaded, the “OpenReadCompleted” event will fire and one can extract the assembly from the XAP. I have chosen to factor into a method the logic used extract the Assembly from the compressed zip file. In the event that we had multiple assemblies we could use Linq to navigate the xml of AppManifest and programmatically load each assembly.
1 2 3 4 5 6 7 8 9 10 | public Assembly LoadAssemblyFromXap(string relativeUriString, Stream xapPackageStream)
{
Uri uri = new Uri(relativeUriString, UriKind.Relative) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | void wcXap1_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if ((e.Error == null) && (e.Cancelled == false))
{
// Convert the downloaded stream into an assembly
Assembly a = LoadAssemblyFromXap("MultipleXap1.dll", e.Result) |
Once the assembly has been extracted, we can create an instance of the selected UserControl by using the “CreateInstance” method on the Assembly object. Based on Microsoft’s documentation, we should have been able to add a project reference to the on-demand XAP, within our default Silverlight Application. This would give us access to that second assemblies types. We can make the reference and the project compiles, but throws an exception at runtime. CreateInstance is not a preferred approach since it drastically limits how we can leverage the strong typing of objects instantiated from this reflected assembly.
Code: MultipleXap.zip

