1
我試圖找出如何導入服務爲我的視圖模型正確......這裏是我的相關代碼(我省略了不重要的東西):PRISM + MEF - 導入服務
ClientBootstrapper的.cs:
public sealed class ClientBootstrapper : MefBootstrapper
{
protected override void ConfigureAggregateCatalog()
{
base.ConfigureAggregateCatalog();
//Add the executing assembly to the catalog.
AggregateCatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
}
protected override DependencyObject CreateShell()
{
return Container.GetExportedValue<ClientShell>();
}
protected override void InitializeShell()
{
base.InitializeShell();
Application.Current.MainWindow = (Window)Shell;
Application.Current.MainWindow.Show();
}
}
ClientShell.xaml.cs:
[Export()]
public partial class ClientShell : Window
{
[Import()]
public ClientViewModel ViewModel
{
get
{
return DataContext as ClientViewModel;
}
private set
{
DataContext = value;
}
}
public ClientShell()
{
InitializeComponent();
}
}
ClientViewModel.cs:
[Export()]
public class ClientViewModel : NotificationObject, IPartImportsSatisfiedNotification
{
[Import()]
private static RandomService Random { get; set; }
public Int32 RandomNumber
{
get { return Random.Next(); } //(2) Then this throws a Null Exception!
}
public void OnImportsSatisfied()
{
Console.WriteLine("{0}: IMPORTS SATISFIED", this.ToString()); //(1)This shows up
}
}
RandomService.cs:
[Export()]
public sealed class RandomService
{
private static Random _random = new Random(DateTime.Now.Millisecond);
public Int32 Next()
{
return _random.Next(0, 1000);
}
}
我得到了所有的進口部分已經被滿足(1)的通知,但後來我得到一個NullReferenceException (2)在ClientViewModel裏面的
return Random.Next();
。不知道爲什麼我得到一個NullReferenceException後,我被告知,所有進口都滿意...
我會接受這個答案,但仍然希望知道是否有辦法導入靜態字段/屬性。 – michael 2011-03-01 20:17:38
@michael MEF不會爲你做。你可以寫一個帶有靜態支持字段的實例屬性,但是因爲MEF可以創建並設置多次,可能不會得到你想要的行爲。 – 2011-03-03 06:13:33