silverlight中常會用到反射來載入一些頁面或控制項,使用反射帶來的問題是調用DLL或XAP中的方法或屬性會很不方便,需要用string定義好方法或類名詞。那麼有沒有一種好的方式可以處理這些問題呢。MEF將會處理這些。
下面我會給出一個簡單的DEMO。
1.建立一個silverlight項目命名“MyMEF”。
2.建立一個silverlight類庫項目,命名“Model”.Model是我們需要反射載入的項目。
3.在Model項目和MyMEF項目中引用“System.componentModel.compostion”。
4.在MyMEF項目中引用“System.componentModel.compostion.Hosting”。
5.MainPage代碼如下:
代碼
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
[Import("model")]
public IModel OurModel { get; set; }
private void button1_Click(object sender, RoutedEventArgs e)
{
string uri = Application.Current.Host.Source.AbsoluteUri;
int index = uri.LastIndexOf("/"); //找出根URL
uri = uri.Substring(0, index) + "/Model.dll";
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler((s1, e1) =>
{
AssemblyPart part = new AssemblyPart();
Assembly ass = part.Load(e1.Result);
//建立Catalog
AssemblyCatalog cata = new AssemblyCatalog(ass);
CompositionContainer container = new CompositionContainer(cata);
CompositionBatch bat = new CompositionBatch();
bat.AddPart(this);
container.Compose(bat);
OurTextBox.Text = OurModel.getData();
});
//啟動非同步下載
client.OpenReadAsync(new Uri(uri));
}
}
6.Model代碼如下:
代碼
public interface IModel
{
string getData();
}
public class ModelHolder
{
[Export("model")]
public IModel OurModel = new DataModel();
}
public class DataModel : IModel
{
#region IModel Members
public string getData()
{
return "Moscow";
}
#endregion
}
7.編譯過後將,Model產生的DLL拷貝到web網站的ClinetBin檔案夾下。這樣一個簡單的MEF項目就OK了。