1

我试图弄清楚如何正确地将服务导入到我的 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
    }
}

随机服务.cs

[Export()]
public sealed class RandomService
{
    private static Random _random = new Random(DateTime.Now.Millisecond);

    public Int32 Next()
    {
        return _random.Next(0, 1000);
    }
}


我确实收到了所有导入部分都已满足的通知 (1),但随后我在 ClientViewModelreturn Random.Next();内部收到了 NullReferenceException (2)。不知道为什么在我被告知所有 Imports 都满足后我会得到 NullReferenceException ......

4

2 回答 2

2

MEF 不会满足静态属性的导入。使随机服务成为实例属性。

于 2011-03-01T18:04:31.323 回答
0

您可以[ImportingConstructor]在构造函数中使用和设置静态属性。

private static RandomService Random { get; set; }

[ImportingConstructor]
public ClientViewModel(RandomService random)
{
   Random = random;
}

只是不要将其设置为静态字段。

于 2011-11-18T10:13:11.897 回答