Dynamically load Assemblies ... Assembly.Load() ... AssemblyPart.Load() ... Silverloght 2.0
This is what I want to do:
I want to dynamically load a class from an extenal assembly into my application. (using Silverlight 2.0 and Visual Studio 2008).
The class which I want to load is called MyAssembly.MyClass; It is derived from Canvas; It resides in an assembly called MyAssembly.dll. I amually deployed the DLL in the ClientBin directory of my Web-Project.
Her is what have tried:
I have tried to load the assembly using Assembly.Load("MyAssembly"). It failed with File not found. (Are there any good working examples for 'Assembly.Load()'?).
Now I am trying to solve the problem with AssemblyPart.Load(...). I am able to load the assembly, but nw I am not able to create instances of objects within that assembly. Can you help?
Here is the code I am working on:
using
System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Reflection;
using System.Net;
using System.IO;
namespace POC_Reflection_Dynamic_Load
{
public partial class Page : Canvas
{
TextBlock txt;
WebClient downloader;
public Page()
{
// Initialize Debug Test Area
txt = new TextBlock();
txt.Text = "";
txt.FontSize = 12;
txt.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 0, 200));
this.Children.Add(txt);
// Download the DLL using a WebClient?
downloader = new WebClient();
downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(onOpenReadCompleted);
downloader.OpenReadAsync(new Uri("MyAssembly.dll", UriKind.Relative));
debug("Downloader Base Address = " + downloader.BaseAddress.ToString());
}
private void onOpenReadCompleted(object o, OpenReadCompletedEventArgs args)
{
loadAssembly(args.Result);
}
private void loadAssembly(Stream s)
{
Assembly a;
try
{
AssemblyPart ap = new AssemblyPart();
ap.Load(s);
debug("Assembly Part successfully loaded: " + ap.Source);
// Here is the problem. Loading the Assembly (DLL) into the AssemblyPart was successful.
// But how do I create an instance of a class which is defined in that DLL? Here is an
// attempt do do that.
//(IT DOES NOT WORK !!!)
Canvas can = (Canvas)Assembly.GetExecutingAssembly().CreateInstance("MyAssembly.MyClass");
if (can == null)
{
debug("can is null!!!!!!!!!");
return;
}
debug("Canvas successfully created");
this.Children.Add(can);
debug("Canvas successfully added");
}
catch (Exception ex)
{
debug("Exception when loading the assembly part:");
debug(ex.ToString());
}
}
public void debug(String s)
{
txt.Text += "\n" + s;
}
}
}