按需加载程序集
本篇主要学习了按需加载程序集。
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
//添加命名空间
using SilverlightClassLibrary;
using System.Windows.Browser;
//实例说明:面的示例代码演示如何从主机服务器按需检索程序集,然后将其加载到当前应用程序域中
//实现的三个步骤
//(1)在Client端应用程序项目中添加了对程序集的引用
//(2)对着程序集右键属性,将程序集的"复制本地"值还必改为"False".非必须,只是为了体现按需下载的好处还是设为false
//(3)将程序集剪切到服务器端的ClientBin目录下(xap所在的目录).
namespace LoadByNeed
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void TextBlock_MouseLeftButtonUp(
object sender, MouseButtonEventArgs e)
{
// Download an "on-demand" assembly.
WebClient wc = new WebClient();
wc.OpenReadCompleted +=new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
//Uri uri = new Uri("http://localhost:1826/SilverlightClassLibrary.dll", UriKind.RelativeOrAbsolute);
//这个方式可以将目录放到Web下的根目录下,这样要添加http头部信息
// Uri uri = new Uri(GetUriHead()+"SilverlightClassLibrary.dll", UriKind.RelativeOrAbsolute);
//该方式只需要将SilverlightClassLibrary.dll复制到ClientBin目录下(xap所在的目录)
Uri uri = new Uri("SilverlightClassLibrary.dll", UriKind.RelativeOrAbsolute);
wc.OpenReadAsync(uri);
}
private void wc_OpenReadCompleted(
object sender, OpenReadCompletedEventArgs e)
{
if ((e.Error == null) && (e.Cancelled == false))
{
// Convert the downloaded stream into an assembly that is
// loaded into current AppDomain.
AssemblyPart assemblyPart = new AssemblyPart();
assemblyPart.Load(e.Result);
DisplayPageFromLibraryAssembly();
}
}
private void DisplayPageFromLibraryAssembly()
{
// Create an instance of the Page class in the library assembly.
Page1 page = new Page1();
// Display the new Page.
this.stackPanel.Children.Add(page);
}
//获取URI头部:
//例如http://localhost:1826/LoadByNeedTestPage.aspx
//截取后:http://localhost:1826/
public static string GetUriHead()
{
string returnValue = string.Empty;
string str = HtmlPage.Document.DocumentUri.ToString();
if (str != null && !str.Equals(string.Empty))
{
int index = str.LastIndexOf('/');
returnValue = str.Substring(0, index + 1);
}
return returnValue;
}
}
}

浙公网安备 33010602011771号