Reputation: 15282
I'm trying to figure out how to import a service into my ViewModel properly... here's my relevant code (I've omitted the unimportant stuff):
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);
}
}
return Random.Next();
inside of the ClientViewModel. Not sure why I would get a NullReferenceException after I'm told that all Imports are satisfied...
Upvotes: 1
Views: 2074
Reputation: 61
You can use [ImportingConstructor]
and set the static property in the constructor.
private static RandomService Random { get; set; }
[ImportingConstructor]
public ClientViewModel(RandomService random)
{
Random = random;
}
Just don't set it to a static field.
Upvotes: 0
Reputation: 16744
MEF won't satisfy imports on a static property. Make the random service an instance property.
Upvotes: 2