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
    }
}

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) がreturn Random.Next();、ClientViewModel の内部で NullReferenceException (2) を受け取ります。すべてのインポートが満たされていると言われた後、なぜ 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 に答える