.NET Tips and Tricks

Blog archive

Dynamically Downloading Classes at Runtime in Silverlight

Through the WebClient and AssemblyPart.Load method, Silverlight lets you download DLLs dynamically at runtime from the server to the client. This lets you defer dragging the DLL to the client until you know you need it.

To use the DLL you'll download at runtime, you still need to add a reference to the DLL in order to get IntelliSense support at design time (and also to get your application to compile). But because you're going to download the class through code at runtime, you don't need to include that DLL in your project. So, after adding a reference to the DLL, you can set its Copy Local to False.

Using the DLL in your Silverlight application is a little awkward. While you instantiate the class with the New keyword, as usual, you must do it in a dedicated method decorated with MethodImpl attribute, passing the NoInlining parameter. Something like this, for instance:

Private Function CreateMyObject() As Object

  Return New MyDynamicClass

End Function

But you can't actually use the resulting object in that method. Instead, to make Silverlight's type checking happy, you need to defer using that class to a completely separate method:
 Private Sub UseMyObject(dc As  Object)
Dim dc As MyDynamicClass = CType(dc, MyDynamicClass)
End Sub

Attempting to instantiate and use the class in the same method will just generate some bewildering error messages.

Posted by Peter Vogel on 09/28/2011 at 1:16 PM

comments powered by Disqus

Reader Comments:

Sat, Oct 1, 2011 Peter Vogel Canada

Andrew: Right on! I discuss MEF in an article on Dynamically Loading Classes at Runtime, elsewhere on this site (http://visualstudiomagazine.com/articles/2011/09/01/pcnet_dynamicload-runtime.aspx) though, unfortunately, I don't reference how Silverlight XAP files specifically.

Fri, Sep 30, 2011 Andrew Smith UK

You can go further than this if you start using MEF. You can dynamically at runtime determin which xap files you want to bring down to the client too, allowing you to really plug and play functionality and modules based on the users rights / system set up...

Add Your Comments Now:

Your Name:(optional)
Your Email:(optional)
Your Location:(optional)
Please type the letters/numbers you see above

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.