【问题标题】:MEF Container.GetExportedValue<T>() instancing not creating separate instancesMEF Container.GetExportedValue<T>() 实例化不创建单独的实例
【发布时间】:2012-01-15 23:57:29
【问题描述】:

我正在尝试从我的目录中实例化一个视图模型

当我使用 Container.GetExportedValue 然后初始化属性时,所有实例的属性都设置为“p”的最终值的值。但是当我使用标准初始化程序时,它们很好。

所以在我的示例中,MEF 实例中的 FormViewModel 的 Name 属性具有这些值

C C C

但在正常情况下示例具有这些值

一个 乙 C

它的行为就像来自 MEF 容器的所有实例之间存在一些共享引用。

      var worker = new BackgroundWorker();
        worker.DoWork += (o, ea) =>
                         {
                             _forms = new ObservableCollection<FormViewModel>(
                                 FormsExplorerRepository.GetForms()
                                     .Select(p =>
                                             {
 // This way of instancing does strange stuff 
                                                 var fvm = Container.GetExportedValue<FormViewModel>();

// This is fine but of course I'm not getting the importing constructor called
                                                 var fvm = new FormViewModel();

                                                 fvm.Workspace = this;
                                                 fvm.FormId = p.FormId;
                                                 fvm.Label = p.Label;
                                                 fvm.Name = p.Name;
                                                 fvm.Disclaimer = p.Disclaimer;
                                                 fvm.CertificationText = p.CertificationText;
                                                 fvm.Schemes = FormViewModelExtensions.InitialiseSchemes(p);
                                                 return fvm;
                                             })
                                     .ToList());
                         };

这里是视图模型的构造函数

    public FormViewModel()
        : base(null, true)
    {

    }

    [ImportingConstructor]
    public FormViewModel(
        IDialogManager dialogs,
        IEventAggregator events)
        : base(null, true)
    {
        _events = events;
        _events.Subscribe(this);

        _dialogs = dialogs;
    }

我在类定义上有一个导出属性

 [Export(typeof(FormViewModel)), PartCreationPolicy(CreationPolicy.NonShared)]
public class FormViewModel 

我希望这里有足够的信息可以帮助某人

【问题讨论】:

    标签: c# mef caliburn.micro


    【解决方案1】:

    我发现了我的错误

    我没有在我的 AddExportedValue 中使用正确的语法(我在这里注释掉的是错误的方式)

    (container, batch) =>
    {
        // batch.AddExportedValue(new FormViewModel());
        batch.AddExportedValue<Func<FormViewModel>>container.GetExportedValue<FormViewModel>);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 2012-06-16
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 2014-06-10
      • 1970-01-01
      相关资源
      最近更新 更多