【问题标题】:PRISM + MEF -- Importing a ServicePRISM + MEF -- 导入服务
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 我会接受这个答案,但仍然想知道是否有办法导入静态字段/属性。
    • @michael MEF 不会为你做这件事。您可以使用静态支持字段或其他内容编写实例属性,尽管由于 MEF 可以多次创建和设置它可能无法获得您想要的行为。
    【解决方案2】:

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

    private static RandomService Random { get; set; }
    
    [ImportingConstructor]
    public ClientViewModel(RandomService random)
    {
       Random = random;
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-03
      • 1970-01-01
      • 2013-03-17
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多