【发布时间】:2011-03-01 14:46:02
【问题描述】:
我正在尝试弄清楚如何将服务正确导入到我的 ViewModel 中...这是我的相关代码(我省略了不重要的内容):
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),但随后我在 ClientViewModel 内部的
return Random.Next(); 上收到 NullReferenceException (2)。不知道为什么在我被告知所有 Imports 都满足后我会得到 NullReferenceException ......
【问题讨论】:
标签: c# dependency-injection service mef prism-4