public class MyContentLoader : INavigationContentLoader
{
private Dictionary<string, Assembly> assemblies = new Dictionary<string, Assembly>();
public MyContentLoader()
{
//Adds current to list of loaded assemblies
Assembly currentAssembly = Assembly.GetExecutingAssembly();
this.AddAssembly(currentAssembly);
}
public IAsyncResult BeginLoad(Uri targetUri, Uri currentUri, AsyncCallback userCallback, object asyncState)
{
var iar = new MyAsyncResult(asyncState);
//Tries to load type from already loaded assemblies
iar.Result = this.TryLoad(targetUri);
//Type not loaded yet, download it asyncronously
if (iar.Result == null)
{
string assemblyName = targetUri.ToString().Split('.')[0];
//Probably it'a an external page not loaded yet...
WebClient client = new WebClient();
client.OpenReadCompleted += (s, e) =>
{
Uri assemblyUri = new Uri(assemblyName + ".dll", UriKind.Relative);
StreamResourceInfo xapPackageSri = new StreamResourceInfo(e.Result, null);
StreamResourceInfo assemblySri = Application.GetResourceStream(xapPackageSri, assemblyUri);
//Load it
Assembly assembly = new AssemblyPart().Load(assemblySri.Stream);
iar.Result = assembly.CreateInstance(targetUri.ToString());
//Add assemblies to list of loaded ones
this.AddAssembly(assembly);
//Page loaded, end asyncronous operation
userCallback(iar);
};
client.OpenReadAsync(new Uri(assemblyName + ".xap", UriKind.Relative));
}
else
{
userCallback(iar);
}
return iar;
}
public bool CanLoad(Uri targetUri, Uri currentUri)
{
return true;
}
public void CancelLoad(IAsyncResult asyncResult) { }
public LoadResult EndLoad(IAsyncResult asyncResult)
{
return new LoadResult((asyncResult as MyAsyncResult).Result);
}
private void AddAssembly(Assembly assembly)
{
string name = assembly.FullName.Split(',')[0];
this.assemblies.Add(name, assembly);
}
private object TryLoad(Uri targetUri)
{
string assemblyName = targetUri.ToString().Split('.')[0];
if (this.assemblies.ContainsKey(assemblyName))
return this.assemblies[assemblyName].CreateInstance(targetUri.ToString());
else
return null;
}
}